9

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?

mikemaccana
  • 81,787
  • 73
  • 317
  • 396
  • Why are you don't use jQuery? – NiLL Nov 24 '12 at 18:34
  • 3
    @NiLL Because JQuery has a lot of code I don't need and querySelector is provided out of the box in most of the environments where the code will run (ie, all current browsers). – mikemaccana Nov 24 '12 at 18:38

1 Answers1

13

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.

mikemaccana
  • 81,787
  • 73
  • 317
  • 396