3

I'm trying to use some jquery in my project and as soon as I tried using it I came across an error in copied code and can't get any google help on it

 var jquery = require('jquery');
 var $ = jquery.create();
                ^
 TypeError: Object function ( w ) {
     if ( !w.document ) {
          throw new Error( "jQuery requires a window with a document" );
     }
     return factory( w );
 } has no method 'create'

Long story:

I'm trying to get plaintext from some html I have.

I hope to use .text() function which supposedly does that.

My resulting code should be:

console.log($(data).text());
Tamil Selvan C
  • 19,232
  • 12
  • 49
  • 68
ditoslav
  • 4,009
  • 10
  • 36
  • 65

4 Answers4

7

try:

var jsdom = require("jsdom").jsdom;
var markup = '<html><body><h1 class="example">Hello World!</h1><p class="hello">Heya Big World!</body></html>';
var doc = jsdom(markup);
var window = doc.parentWindow;
var $ = require('jquery')(window)
console.log($('.example').text());

Basically you can use the jsdom module to create a DOM out of your markup and then you can use it as you would with jquery in the browser.

AJ Meyghani
  • 4,120
  • 1
  • 29
  • 34
  • Thanks for line 5 `var $ = require('jquery')(window)` that's postponed my trip to the jQuery Insane Asylum by a couple of weeks! – Robin Feb 16 '16 at 11:14
3

You can't use jquery on server as it explicitly requires window and window.document. Try cheerio

vkurchatkin
  • 12,839
  • 2
  • 43
  • 52
  • Yeah. Seems like I can't. Unfortunately cheerio doesn't have something simple for html->plaintext but I'll keep looking – ditoslav Dec 30 '13 at 11:44
  • 2
    This doesn't seem to make sense to me. What is the use of having a jQuery module for Node.js if it can't be used server-side? I mean, if I want to use it client-side then I'll just include it on the page. – sveti petar Jan 18 '14 at 14:29
  • so, there is no jQuery for Node.js, that's the problem. The fact that it's on npm doesn't make it Node.js module. – vkurchatkin Jan 18 '14 at 15:38
  • 2
    There are libraries which allow you to use jQuery on the server side: http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js – Daniel Flippance Jan 27 '14 at 22:45
2

I had the same problem. To solve it I installed an older version of jquery: npm install jquery@1.8.3

stropitek
  • 1,247
  • 11
  • 23
1

It used to work just fine for many months. But then they changed something and now it doesn't. I could run jquery without a window just fine and it worked perfectly on node js. But not with the latest version for some reason. Really weird.

What we are trying to do is just this:

$ = require("jquery"); $("..).find(".message").html("Hello World!");

Martin
  • 3,332
  • 3
  • 23
  • 29