a blog for those who code

Wednesday 4 November 2015

Exploring JSDOM in Node.js

In this post we will be exploring JSDOM in Node.js. JSDOM generates a Document Object Model (DOM) from few lines of HTML, from an HTML file or from web page loaded via URL. It is a JavaScript implementation of the WHATWG DOM and HTML Standards, for use with Node.js.

To install JSDOM module, you need to run the following command :

npm install jsdom

Usage of JSDOM

var jsdom = require("jsdom");
jsdom.env({
  '<div id="myDiv" class="divClass">Coding Defined</div>', function (err, window) {
    if(err) console.log(err);
    console.log(window);
  }
});

When we run the above code we will get something like below where we have client side objects like document, addEventListener, setTimeout, window etc. We can actually use these objects in server side as we use them in client side.


Lets say you want to get the div by its id in, then you can write the below code.

jsdom.env(
  '<div id="myDiv" class="myClass">Coding Defined</div>', function (err, window) {
    if(err) console.log(err);
    var localWindow = window;
    var myDiv = localWindow.document.getElementById('myDiv');
    console.log(myDiv.innerHTML);
});

The output of the above code is :


With JSDOM you will get methods, properties and collection of attributes, all the data and functionality that you can expect to see in W3C DOM in a browser. To avail the jQuery functionality you need to include the URL of the recent verion of jQuery like below :

jsdom.env(
  '<div id="myDiv" class="myClass">Coding Defined</div>',
    ['http://code.jquery.com/jquery-1.7.1.min.js'],
    function (err, window) {
      if(err) console.log(err);
      console.log(window);
});

Please Like and Share the CodingDefined Blog, if you find it knowledgeable and helpful.

1 comment:

  1. Thank you very much for the explanation and code.. :)

    ReplyDelete