What is happy-dom?
happy-dom is a fast and lightweight DOM implementation for Node.js. It is designed to be compatible with the browser's DOM API, making it useful for server-side rendering, testing, and other scenarios where a DOM is needed outside of a browser environment.
What are happy-dom's main functionalities?
DOM Manipulation
happy-dom allows you to create and manipulate DOM elements just like you would in a browser environment. This is useful for server-side rendering and testing.
const { Window } = require('happy-dom');
const window = new Window();
const document = window.document;
const div = document.createElement('div');
div.textContent = 'Hello, World!';
document.body.appendChild(div);
console.log(document.body.innerHTML); // <div>Hello, World!</div>
Event Handling
happy-dom supports event handling, allowing you to add event listeners and dispatch events. This is useful for testing event-driven code.
const { Window } = require('happy-dom');
const window = new Window();
const document = window.document;
const button = document.createElement('button');
button.textContent = 'Click me';
button.addEventListener('click', () => {
console.log('Button clicked!');
});
document.body.appendChild(button);
// Simulate a click event
const event = new window.Event('click');
button.dispatchEvent(event); // Button clicked!
Querying DOM Elements
happy-dom allows you to query DOM elements using methods like `querySelector` and `querySelectorAll`. This is useful for selecting and manipulating specific elements in the DOM.
const { Window } = require('happy-dom');
const window = new Window();
const document = window.document;
document.body.innerHTML = '<div class="test">Hello</div><div class="test">World</div>';
const elements = document.querySelectorAll('.test');
console.log(elements.length); // 2
console.log(elements[0].textContent); // Hello
console.log(elements[1].textContent); // World
Other packages similar to happy-dom
jsdom
jsdom is another popular DOM implementation for Node.js. It provides a more complete and detailed implementation of the DOM and other web standards. However, it is generally slower and more resource-intensive compared to happy-dom.
cheerio
cheerio is a fast, flexible, and lean implementation of core jQuery designed specifically for the server. It is not a full DOM implementation but provides a subset of jQuery functionality for parsing and manipulating HTML. It is faster and more lightweight than jsdom but less feature-rich.
linkedom
linkedom is a lightweight and fast DOM implementation for Node.js. It aims to be a minimalistic alternative to jsdom, providing essential DOM functionalities with better performance. It is similar to happy-dom in terms of performance and use cases.
Happy DOM
A "jsdom" alternative with support for server side rendering of web components.
As shadow roots are closed, this DOM supports opening them up by providing an option. When the shadow roots are opened up, Happy DOM will scope the HTML and CSS.
DOM Features
How to Install
npm install happy-dom
Usage
Server Side Rendering
Happy DOM provide with a utility for server side rendering. The utility will create a VM context, which is an isolated environment for where the script and DOM can be executed.
Importing dependencies is not supported by the VM script. Therefore scripts with imports has to be bundled with a tool like Webpack in order to be executed within the virtual machine.
Example
import { VMContext } from 'happy-dom';
import { Script } from 'vm';
const vm = new VMContext();
const html = `
<html>
<head>
<title>Test page</title>
</head>
<body>
<div class="myContainer">
<!–– Content will be added here -->
</div>
</body>
</html>
`;
const script = new Script(`
const element = document.createElement('div');
const myContainer = document.querySelector('.myContainer');
element.innerHTML = 'Test';
myContainer.appendChild(element);
`);
const url = 'http://localhost:8080';
const openShadowRoots = true;
const result = vm.render({ html, script, url, openShadowRoots });
console.log(result);
Create a Synchronous DOM
This section will explain how to create a synchronous DOM for parsing HTML and much more.
Note: You might have to import the Window class as a single import if you wish to use it client side. Path: "happy-dom/lib/Window" .
import { Window } from 'happy-dom';
const window = new Window();
const document = window.document;
document.body.innerHTML = `
<div class="myContainer">Test</div>
`;
const myContainer = document.querySelector('.myContainer');
console.log(myContainer.innerHTML);
Create an Asynchronous DOM
The asynchronous DOM will add features like "fetch", "setTimeout", "setInterval" etc. on top of the synchronous DOM.
An asynchronous DOM is useful when running scripts inside of it. This is usually done within a VM context. See the "Manually Setup a VM Context" section for an example on how to set this up.
Note: The asynchronous DOM has a dependency to "node-fetch", so it will not work client side.
import { AsyncWindow } from 'happy-dom';
const window = new AsyncWindow();
const document = window.document;
document.body.innerHTML = `
<div class="myContainer">Test</div>
`;
window.fetch('http://localhost:8080/json').then(response => {
response.json().then(data => {
const myContainer = document.querySelector('.myContainer');
myContainer.innerHTML = data.test;
})
});
window.whenAsynComplete().then(() => {
const myContainer = document.querySelector('.myContainer');
console.log(myContainer.innerHTML);
});
Manually Setup a VM Context
The bellow example will show you how to setup a Node VM context.
import { AsyncWindow } from 'happy-dom';
import { Script, createContext } from 'vm';
const asyncWindow = new AsyncWindow();
const global = Object.assign({}, asyncWindow, { window: asyncWindow });
const context = createContext(global);
const window = context.window;
const html = `
<html>
<head>
<title>Test page</title>
</head>
<body>
<div class="myContainer">
<!–– Content will be added here -->
</div>
</body>
</html>
`;
const script = new Script(`
const element = document.createElement('div');
const myContainer = document.querySelector('.myContainer');
element.innerHTML = 'Test';
myContainer.appendChild(element);
`);
window.location.href = 'http://localhost:8080';
window.shadowRootRenderOptions.openShadowRoots = true;
window.whenAsyncComplete().then(() => {
const myContainer = window.document.querySelector('.myContainer div');
console.log(myContainer.innerHTML);
});
document.write(html);
script.runInContext(context);
Known Limitations
Happy DOM supports the most common functionality of a DOM, but there are some features that are not supported yet.
If you have a need for a missing feature or if you have found a bug, please let me know, and I will do my best to fix it.
Release Notes
Version | Date | Description |
---|
0.2.0 | 2019-09-20 | Adds support for SVGSVGElement, SVGElement and SVGGraphicsElement. |
0.1.0 | 2019-09-19 | Adds support for HTMLInputElement, HTMLTextAreaElement, HTMLFormElement, Range and DOMRect (bounding client rect). |
0.0.1 | 2019-09-13 | Initial release. |
How to Develop
Installation
npm install
Compilation
npm run compile
Run Watcher
npm run watch