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());
7
  • 3
    You're probably doing the wrong thing entirely. What are you trying to do? Commented Dec 30, 2013 at 2:25
  • Are you using this library? Commented Dec 30, 2013 at 2:27
  • I added "jquery":">= 0.0.0", to my dependencies Commented Dec 30, 2013 at 2:29
  • 2
    It seems that you are using jQuery on the server side (so inside node.js) and jQuery tries to find the document of the browser window. But since you are not running inside a browser it can not find any document. I am afraid SLaks comment is spot on. Commented Dec 30, 2013 at 2:38
  • are you running on windows (OS) Commented Dec 30, 2013 at 2:40

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for line 5 var $ = require('jquery')(window) that's postponed my trip to the jQuery Insane Asylum by a couple of weeks!
3

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

4 Comments

Yeah. Seems like I can't. Unfortunately cheerio doesn't have something simple for html->plaintext but I'll keep looking
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.
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.
There are libraries which allow you to use jQuery on the server side: stackoverflow.com/questions/1801160/…
1

I had the same problem. To solve it I installed an older version of jquery: npm install [email protected]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.