I would like to use JSDom to perform some server-wise DOM manipulation. However, despite explcitly enabling querySelector, it is undefined in the documents created:
var jsdom = require('jsdom');
// Yep, we've got QuerySelector turned on
jsdom.defaultDocumentFeatures = {
QuerySelector: true
};
var dom = jsdom.defaultLevel;
var document = jsdom.jsdom("<html><body><h1>Hello StackOverflow</h1></body></html>"),
window = document.createWindow();
However:
console.log(document.querySelector)
Returns
undefined
How can I make document.querySelector work properly using jsdom?
Found the answer to this one myself.
JSDom has a 'default document' as well as support for multiple additional documents.
My original understanding was that enabling QuerySelector on the default document would enable it on all documents. This was incorrect.
I needed to enable QuerySelector on the (non-default) document I was creating.
Working code below:
var jsdom = require('jsdom');
var dom = jsdom.defaultLevel;
// QuerySelector must be turned on on the specificdocument we're creating
var document = jsdom.jsdom("<html><body><h1>Hello</h1></body></html>", null, {
features: {
QuerySelector: true
}
}),
window = document.createWindow();
Running
console.log(document.querySelector)
Now shows the function exists.