How to Use jQuery in Node. js and Node. js

Source: Internet
Author: User

How to Use jQuery in Node. js and Node. js

Want to use jQuery in NodeJs?

First, install jquery and npm install jquery. The installed version is 3.1.0.

Next, first we will use var $ = require ('jquery ').

Save the following code as app. js

var $ = require('jquery')$("body").append("<div>TEST</div>");console.log($("body").html());

Run node app. js. Error message:

Error: jQuery requires a window with a document

So what should we do?

On the jquery installation package home page of npm, we can use jsdom to simulate a document.

require("jsdom").env("", function(err, window) {  if (err) {    console.error(err);    return;  }  var $ = require("jquery")(window);  $("body").append("<div>TEST</div>");  console.log($("body").html());});

Run and the result is OK.

The above code makes it uncomfortable for me to perform operations in the callback function. So how can we introduce jquery In the callback function?

var $ = require('jquery')(require("jsdom").jsdom().defaultView);$("body").append("<div>TEST</div>");console.log($("body").html());

Run OK.

The above is all the content shared in this article. I hope it will be helpful for you to learn node. js.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.