Edit elements in the jsdom window and save the window as a new HTML file?

Eva picture Eva · May 8, 2015 · Viewed 8.8k times · Source

I want to load an HTML file (using fs.read), load the DOM using jsdom, and then change the text of the nodes of the body (via jquery). Then I want to save the edited DOM window as an HTML file. Is there a way to do this? The code I am using is the following:

fs.readFile(file, 'utf8', function(error, data) {
    jsdom.env(data, [], function (errors, window) {
        var $ = require('jquery')(window);
        $(document.body.getElementsByTagName("*")).each(function () {
            var content = $(this).text();
            var word = "\\b"+wordSuggestions.word+"\\b";
            var re = new RegExp(word, "g");
            content = content.replace(re, wordSuggestions.suggestion);
            $(this).text(content);
        });

        fs.writeFile(file, data, function (error){ // saving the new HTML file? What should I put instead of data? Window?
        });
    });
});

Answer

Louis picture Louis · May 8, 2015

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;
        });
    });
});