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,913
  • 12
  • 49
  • 70
ditoslav
  • 4,563
  • 10
  • 47
  • 79

3 Answers3

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,389
  • 1
  • 31
  • 35
  • 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
  • 13,364
  • 2
  • 47
  • 55
  • 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
1

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

stropitek
  • 1,304
  • 1
  • 11
  • 23