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?
This worked for me
var jsdom = require('jsdom'); $ = require('jquery')(new jsdom.JSDOM().window);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With