jsdom - document.querySelector enabled, but is missing from document

mikemaccana picture mikemaccana · Nov 24, 2012 · Viewed 10.2k times · Source

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?

Answer

mikemaccana picture mikemaccana · Nov 24, 2012

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.