Reputation: 3797
I installed jQuery for Node with the line:
npm install jquery
In the beginning of my server-side Node.js code, I put this:
var $ = require('jquery');
It installed fine and the module is visible on my server. Now, I'm trying to do this in that same file:
$.each(rows, function(num, row){
console.log(row.username);
});
But I get the following error:
TypeError: Object function ( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
} has no method 'each'
at Query._callback (/home/lights/public_html/apps/node_servers/fircik_gamelist.js:69:5)
It says it 'has no method each' which I don't understand because, obviously, jQuery should have that method. Before I installed the jQuery module, I tried to run the same code and it gave the error ReferenceError: $ is not defined
, and that error is no longer present after installation completed successfully.
So what am I missing here?
What does it mean when it says 'jQuery requires a window with a document'?
Upvotes: 1
Views: 255
Reputation: 46320
jQuery is a library created for clientside javascript (javascript that runs in a web browser). Javascript that runs in a webbrowser has a window
and a document
object. Javascript that runs on the server (Node.js) doesn't have that (because it doesn't have a window
or document
of course..).
So that might be the reason jQuery doesn't work on the server side.
You can also do loop through the elements of an array with native javascript:
for(var i = 0; i < rows.length; i++) {
console.log(rows[i].username);
}
Or (as Pointy pointed out) with the native .forEach() function on the Array prototype:
rows.forEach(function(row) {
console.log(row.username);
});
Upvotes: 1