Edit elements in the jsdom window and save the window as a new HTML file?
Here's an example of how to do it. I've based it on your code but simplified it a bit so that I'd have code that executes and illustrates how to do it. The following code reads foo.html
and adds the text modified!
to all p
element and then writes it out to out.html
. The main thing you were missing is window.document.documentElement.outerHTML
.
var jsdom = require("jsdom");
var fs = require("fs");
fs.readFile('foo.html', 'utf8', function(error, data) {
jsdom.env(data, [], function (errors, window) {
var $ = require('jquery')(window);
$("p").each(function () {
var content = $(this).text();
$(this).text(content + " modified!");
});
fs.writeFile('out.html', window.document.documentElement.outerHTML,
function (error){
if (error) throw error;
});
});
});
There's no jsdom.env()
anymore, and I think this example is easier to understand:
const fs = require('fs');
const jsdom = require('jsdom');
const jquery = require('jquery');
fs.readFile('1.html', 'utf8', (err, data) => {
const dom = new jsdom.JSDOM(data);
const $ = jquery(dom.window);
$('body').html('');
fs.writeFile('2.html', dom.serialize(), err => {
console.log('done');
});
});