Jsdom - document.query Selection enabled but missing in document

I would like to use JSDom to do some DOM manipulations on the server. However, even though it explicitly includes querySelector, the generated documents are undefined:

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 correctly using jsdom?

+6
source share
1 answer

I found the answer to this myself.

JSDom has a "default document" and also supports several additional documents.

My initial understanding was that including QuerySelector in a document by default would enable it in all documents. This is not true.

I needed to include a QuerySelector in the (non-standard) document that I was creating.

Work 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(); 

Launch

 console.log(document.querySelector) 

Now shown the function exists.

+10
source

All Articles