Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: jQuery requires a window with a document

Tags:

jquery

node.js

So everything was working just fine and great until doing npm update and now things do not work quite as they used to.

A little background: in my code I use jquery to parse textual html. I do not use a window and I don't use jsdom. It used to work just fine to do this:

$ = require("jquery");  $(html).find("<h1>").html("The title");  

But now I get this: jQuery requires a window with a document

How do I fix this?

like image 631
Martin Avatar asked Jan 26 '14 00:01

Martin


2 Answers

This worked for me

var jsdom = require('jsdom'); $ = require('jquery')(new jsdom.JSDOM().window); 
like image 129
Aravinthan K Avatar answered Oct 15 '22 21:10

Aravinthan K


The npm package for jQuery definitely used to include jsdom with it, which is why it would work at all in Node: jQuery needs to have some kind of DOM environment to work with.

You can check that old versions used to have it by doing npm install [email protected]. You'll see jsdom being installed with it. For some reason they seem to have removed jsdom from the recent releases. I don't know why.

However, using jsdom 7.x to run jQuery code is simple:

var jsdom = require("jsdom"); var window = jsdom.jsdom().defaultView;  jsdom.jQueryify(window, "http://code.jquery.com/jquery.js", function () {   var $ = window.$;   $("body").prepend("<h1>The title</h1>");   console.log($("h1").html()); }); 

The path could be changed to a different version of jQuery or to a local file.

Note: Earlier versions of jsdom, including the 3.x series, would need the line var window = jsdom.jsdom().parentWindow; instead of var window = jsdom.jsdom().defaultView;. 4.x made it so that parentWindow no longer works.

like image 42
Louis Avatar answered Oct 15 '22 21:10

Louis