-1

I'm trying to use Node to debug a Javascript file that contains some JQuery. but when loading files it gets not recognized on $. I've installed JQuery to local package (npm install jquery -save-dev).

"npm jquery -version" result is 6.9.8

Code:

$("#modalAddRole").on("modal:visible", function () {
    $("#roleName").val("");
    $("#roleName").focus();
});
Kiran Mistry
  • 2,614
  • 3
  • 12
  • 28
SteinTheRuler
  • 3,549
  • 4
  • 35
  • 71

2 Answers2

2

jQuery manipulates the dom.

node.js does not have a dom.

You'll need to create a virtual dom (that does not display)

for that use jsdom to load your webpage/app and then execute whatever dom manipulation code you want.

Example:

const jsdom = require("jsdom");
const {JSDOM} = jsdom;
const jquery = require('jquery');

JSDOM.fromURL("https://url_To_Your_WebPage_Local_Or_Remote.com")
  .then(dom => {
    const $ = jquery(dom.window);
    //your jQuery code here
  })
Maher Fattouh
  • 1,742
  • 16
  • 24
0

I've installed JQuery to local package

Installing it isn't enough. You need to load it into your program…

const $ = require('jquery');

… and then $("#modalAddRole") isn't going to do anything until you load your HTML into it.

See the documentation:

For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as jsdom. This can be useful for testing purposes.

require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});

But this seems like a very complicated approach to getting a debugging environment running. Assuming the production environment for the code in the browser, it would make a lot more sense to debug it in the browser.

Browsers have excellent debugging tools built-in these days, and simulating all the things browsers do by default is likely to make debugging harder because the debug environment is signficantly different to the production environment.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335