Shane Abram Mendez Shane Abram Mendez - 5 months ago 60
HTML Question

Jsdom not returning document

I am trying to use jsdom to load a local HTML file, this is the code

var config = {
file: "filename",
scripts: ["node_modules/jquery/dist/jquery.min.js"]
done: function(err, window){
console.log(window.document.URL)
console.log(window.document.children)
}
}
jsdom.env(config)


window.document.URL
displays the correct url, but
window.document.innerHTML
doesnt have any data. Ive even tried

var config = {
text: *raw-html*,
scripts: ["node_modules/jquery/dist/jquery.min.js"]
done: function(err, window){
console.log(window.document.children)
}
}


but I had the same results, any help?

Update



I have found that

var rawhtml = fs.readFileSync("filename.html","utf8")
jsdom.env(
rawhtml,
["http://code.jquery.com/jquery.js"],
function (err, window) {
console.log(window.$("html").html())
}
);


works as expected (it logs everything inside the
html
tags)

I then found that

config = {
file: "filename.html",
scripts: ["http://code.jquery.com/jquery.js"],
done: function (err, window) {
var $ = window.$;
console.log($("html").html());
}
}
jsdom.env(config);


also works, but again neither will create the
document
object correctly

"Solution"



jsdom does not show the output of
document.children
in the same way a browser console would, however, all of the functionality you would expect is there. I found this extremely confusing, and the confusion was only exacerbated by the fact that I was following incorrect guides to jsdom. I hope my post will help anyone experiencing the same issues. I will post a final working
document
object below

var code = function(document){
console.log(document.body.innerHTML)
document.body.innerHTML = "i changed the body"


}
function getdoc(file, func){
var document;
jsdom.env(
file,
(err, window) => {
document = window.document
func(document)
}
);
}
getdoc(index.html",code)


I use
jsdom.env()
to get the
document
, then pass the
document
to
func
where all the fun javascript magic is free to happen. Keep in mind that any changes made to the
document
need to be manually saved.

Answer

There is no document.innerHTML property.

Check "innerHTML" in document; -you'll get false.

Comments