Security News
JavaScript Leaders Demand Oracle Release the JavaScript Trademark
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
happy-dom
Advanced tools
A jsdom alternative with support for server side rendering of web components.
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.
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
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 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 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.
A "jsdom" alternative with support for server side rendering of web components.
As shadow roots are scoped, 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.
Custom Elements (Web Components)
Shadow Root (Shadow DOM)
Mutation Observer
Tree Walker
Fetch
And much more..
npm install happy-dom
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.
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 = await vm.render({ html, script, url, openShadowRoots });
// Will output HTML with a div element inside the "myContainer" element
console.log(result);
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');
// Will output "Test"
console.log(myContainer.innerHTML);
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.whenAsyncComplete().then(() => {
const myContainer = document.querySelector('.myContainer');
// Will output the value in "data.test"
console.log(myContainer.innerHTML);
});
The bellow example will show you how to setup a Node VM context.
import { AsyncWindow } from 'happy-dom';
import VM from 'vm';
const context = VM.createContext(new AsyncWindow());
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 VM.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');
// Will output "Test"
console.log(myContainer.innerHTML);
});
script.runInContext(context);
document.write(html);
As mentioned above, Happy DOM comes with render options for opening the shadow roots for server side rendering.
Opening shadow roots will render them opened when running innerHTML or outerHTML, but they will not be modified in the DOM tree.
By default CSS will be scoped and attached to the head. The most common use case is render the entire document element by running "document.documentElement.outerHTML", which will include the head with the CSS.
The shadow root options are available under "window.shadowRootRenderOptions".
Name | Default value | Description |
---|---|---|
openShadowRoots | false | Opens the shadow root when rendering elements with innerHTML or outerHTML. |
appendScopedCSSToHead | true | Set to "true" to append extracted and scoped CSS to the head extracted when "openShadowRoots" is enabled. The CSS will still be extracted when set to "false". It will be available in the "cssCache". |
cssCache | new ScopedCSSCache() | CSS cache object with the extracted CSS. |
const allScopedCSS = window.shadowRootOptions.cssCache.getAllScopedCSS();
// Outputs all extracted CSS
console.log(allScopedCSS);
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.
Version | Date | Description |
---|---|---|
0.5.0 | 2019-10-21 | Adds support for click(), focus() and blur(). (#8) |
0.4.4 | 2019-10-20 | Fixes issue with CustomEvent not being defined correctly causing issues with detail property. (#10) |
0.4.3 | 2019-10-08 | Fixes issue with cloned nodes referring to the same attributes, which is causing weird issues in lit-html. (#5) |
0.4.2 | 2019-10-08 | Fixes issue where query selector not returning correct elements. (#2) |
0.4.1 | 2019-10-07 | Fixes issue with self closing elements become parent of next element in HTMLParser. (#1) |
0.4.0 | 2019-10-07 | Adds type and eventInit to Event constructor. (#4) |
0.3.1 | 2019-10-07 | Fixes bug where global.Error is undefined. (#6) |
0.3.0 | 2019-10-06 | Adds support for scrollTop, scrollLeft, scrollTo(), offsetLeft, offsetTop offsetHeight, offsetWidth. |
0.2.16 | 2019-10-06 | Major bug fixes with server side rendering. |
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. |
npm install
npm run compile
npm run watch
FAQs
Happy DOM is a JavaScript implementation of a web browser without its graphical user interface. It includes many web standards from WHATWG DOM and HTML.
The npm package happy-dom receives a total of 776,629 weekly downloads. As such, happy-dom popularity was classified as popular.
We found that happy-dom demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.