Open In App

How to use jQuery with Node.js ?

Last Updated : 15 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

jQuery is a JavaScript library, which provides us with the same functionality as vanilla JavaScript but in fewer lines of code. The need for jQuery is reduced as doing things became much simpler in vanilla JavaScript with updates. Although its popularity is decreasing, still around 76% of the projects use jQuery.

Our Aim is to use jQuery with Node.js: We can use jQuery in Node.js using the jquery module. 

Note: Use the ‘jquery’ module not the ‘jQuery’ module as the latter is deprecated.

Getting jQuery to work in Node.js:

  • Step 1 : Making the package.json file. Use the following command to create the package.json file, which keeps track of the modules and dependencies. 

    npm init -y

    The ‘-y’ tag makes yes the default answer for all the questions asked while creating the package.json file.

  • Step 2: Installing the jquery module. Use the following command to install the jquery module.

    npm install jquery
  • Step 3 :Installing the jsdom module. Since jQuery is a frontend JavaScript Library, it needs to have a window with a document to work in the backend. ‘jsdom’ is a library that is used to parse and interact with the HTML. It is not exactly a web browser but mimics one. Use the following command to install the jsdom module.

    npm install jsdom
  • Step 4 :Importing the jsdom module. Use the require method to import the jsdom module.

    const jsdom = require('jsdom')
  • Step 5: Creating a new window. We create a window with a document by creating a JSDOM object, with the HTML code as the parameter. Following code is used to create a window with a document :- 

    const dom = new jsdom.JSDOM("")
  • Step 6: Importing jQuery and providing it with a window. Once the window with a document is created, we can use the jquery module by providing it with the window we created. The following code is used to import the jquery module.

    const jquery = require('jquery')(dom.window)

That’s it we have successfully loaded jquery into our Node.js application.

Example: To get a better understanding of how it works, please go through the below example :- 

Javascript




// Importing the jsdom module
const jsdom = require("jsdom");
  
// Creating a window with a document
const dom = new jsdom.JSDOM(`<!DOCTYPE html>
<body>
<h1 class="heading">
    GeeksforGeeks
</h1>
</body>
`);
  
// Importing the jquery and providing it
// with the window
const jquery = require("jquery")(dom.window);
  
// Appending a paragraph tag to the body
jquery("body").append("<p>Is a cool Website</p>");
  
// Getting the content of the body
const content = dom.window.document.querySelector("body");
  
// Printing the content of the heading and paragraph
console.log(content.textContent);


Output:

GeeksforGeeks
Is a cool website

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads