2

I'm having trouble getting jQuery to produce any kind of result with NodeJS. I followed this post to actually get it to work through Node, so now my page displays. However none of the code I write in jQuery actually does anything.

Just to be extra sure I copied the example from jquery.com exactly, but that also fails to work. The console doesn't tell me anything either.

Here's my code

index.html:

<html>
<body>

 <p>
   <b>Click</b> to change the <span id="tag">html</span>
 </p>
 <p>
   to a <span id="text">text</span> node.
 </p>
 <p>
   This <button name="nada">button</button> does nothing.
 </p>
</body>
</html>

header.js

var http = require('http');
var fs = require('fs');
var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;

var $ = jQuery = require('jquery')(window);

http.createServer(function (req, res) {
  fs.readFile('/home/leonardo/Desktop/Header/index.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });

}).listen(8080);

$( "p" ).click(function() {
  var htmlString = $( this ).html();
  $( this ).text( htmlString );
});

I'm very new to Node and also very confused.

1
  • jQuery should be used on client side, while you're trying to use that on server side. Node.js is hosting the application, you should instead create a separate javascript file, include jQuery in your html, and include your script in your html file. Node.js, in your case, is a terminal application, hence it doesn't own a DOM. Commented Oct 19, 2018 at 14:25

1 Answer 1

1

Node.js is backend side of your app, jQuery work at frontend side, in browser. Create separate file for jQuery, for frontend code, and add this file to the index.html.

<html>
<body>

 <p>
   <b>Click</b> to change the <span id="tag">html</span>
 </p>
 <p>
   to a <span id="text">text</span> node.
 </p>
 <p>
   This <button name="nada">button</button> does nothing.
 </p>
<script src="index.js"></script>
</body>
</html>

and jQuery file index.js

 $( "p" ).click(function() {
  var htmlString = $( this ).html();
  $( this ).text( htmlString );
 });
Sign up to request clarification or add additional context in comments.

3 Comments

Is there really no way to not have to link my js script inside my html?
Yes, no way, node works on server, jQuery on browser.
@Eight — You have two different programs which run on two different computers and in two different environments (browser, node). The fact they use the same programming language is irrelevant.

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.