문제

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?

도움이 되었습니까?

해결책 2

Following the JSDOM documentation, here the updated code for version 16.6.0:

const { JSDOM } = require("jsdom");

const dom = new JSDOM("<html><body><h1>Hello</h1></body></html>");
const document = dom.window.document;

console.log(document.querySelector);

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top