Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic error when using jquery with nodejs

Tags:

jquery

node.js

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());
like image 957
ditoslav Avatar asked Sep 27 '26 23:09

ditoslav


1 Answers

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.

like image 106
AJ Meyghani Avatar answered Sep 29 '26 19:09

AJ Meyghani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!