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.

lpetrucci
  • 1,285
  • 4
  • 22
  • 40
  • 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. – briosheje Oct 19 '18 at 14:25

1 Answers1

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 );
 });
Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
  • Is there really no way to not have to link my js script inside my html? – lpetrucci Oct 19 '18 at 14:28
  • Yes, no way, node works on server, jQuery on browser. – Kamil Naja Oct 19 '18 at 14:29
  • 2
    @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. – Quentin Oct 19 '18 at 14:32