In a nutshell, jsdom is a JavaScript-based implementation of the W3C Document Object Model (DOM) for Node.js. But, what does it mean? What do we need it for? Imagine you need to manipulate DOM from a raw HTML on the server side in a Node.js app, such as Express and Koa apps, but there is no DOM on the server side and hence there isn't much you can do. This is when jsdom comes to our rescue. It turns the raw HTML into a DOM fragment that works like the DOM on the client side, but inside Node.js. And then, you can use a client-side JavaScript library such as jQuery to manipulate the DOM on Node.js like a charm. The following is an example of basic usage of this for server-side apps:
- Import jsdom on a server-side app:
import jsdom from 'jsdom'
const { JSDOM } = jsdom
- Pass in a string of any raw HTML to the JSDOM constructor and you will get back a DOM object:
const dom = new JSDOM(<!DOCTYPE html><p>Hello World</p>)
console.log(dom.window...