JSDOM: JavaScript DOM Implementation for Node.js

29.0.2 · active · verified Sun Apr 19

jsdom is a pure-JavaScript implementation of many web standards, including the WHATWG DOM and HTML specifications, designed for use within Node.js. Its primary goal is to emulate a sufficient subset of a web browser environment, making it highly useful for server-side testing, web scraping, and automation of web applications without a full browser GUI. The current stable version is 29.0.2. Releases seem to follow a relatively frequent cadence, with minor and patch versions appearing regularly to address bugs, improve performance, and add features, while major versions introduce breaking changes and significant overhauls, such as the recent CSSOM rewrite in v29.0.0 and resource loading changes in v28.0.0. Key differentiators include its pure-JS nature, making it lightweight compared to headless browser solutions, and its direct exposure of the DOM API, enabling direct manipulation and inspection of rendered HTML.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating a JSDOM instance, accessing its window and document, manipulating elements, simulating user interaction, and proper cleanup.

import { JSDOM } from 'jsdom';

// Basic usage: create a DOM from an HTML string
const dom = new JSDOM(`<!DOCTYPE html>
  <html>
    <head><title>My Page</title></head>
    <body>
      <p id="greeting">Hello, JSDOM!</p>
      <button onclick="document.querySelector('#greeting').textContent = 'Button Clicked!';">Click Me</button>
    </body>
  </html>`, {
  url: "https://example.org/",
  referrer: "https://example.com/",
  contentType: "text/html",
  includeNodeLocations: true // Useful for debugging script errors
});

const { window } = dom;
const { document } = window;

// Access and manipulate the DOM
console.log(document.title); // My Page
const greetingParagraph = document.getElementById("greeting");
console.log(greetingParagraph?.textContent); // Hello, JSDOM!

// Simulate a click event, executing inline script
const button = document.querySelector('button');
button?.click();
console.log(greetingParagraph?.textContent); // Button Clicked!

// Clean up the window object to prevent memory leaks
dom.window.close();

view raw JSON →