What is linkedom?
Linkedom is a lightweight, fast, and efficient library for working with DOM and HTML in Node.js environments. It provides a comprehensive set of APIs to manipulate and traverse the DOM, similar to what you would find in a browser environment.
What are linkedom's main functionalities?
DOM Manipulation
This feature allows you to parse HTML strings and manipulate the DOM elements. In this example, we parse an HTML string, select a div element by its ID, change its text content, and then output the modified HTML.
const { parseHTML } = require('linkedom');
const { document } = parseHTML('<html><body><div id="app"></div></body></html>');
const appDiv = document.getElementById('app');
appDiv.textContent = 'Hello, World!';
console.log(document.toString());
Event Handling
Linkedom supports event handling similar to browser environments. This example demonstrates how to add an event listener to a button element and dispatch a click event programmatically.
const { parseHTML } = require('linkedom');
const { document, Event } = parseHTML('<html><body><button id="btn">Click me</button></body></html>');
const button = document.getElementById('btn');
button.addEventListener('click', () => console.log('Button clicked!'));
const event = new Event('click');
button.dispatchEvent(event);
CSS Selector Queries
You can use CSS selectors to query elements in the DOM. This example shows how to select all list items with a specific class and log their text content.
const { parseHTML } = require('linkedom');
const { document } = parseHTML('<html><body><ul><li class="item">Item 1</li><li class="item">Item 2</li></ul></body></html>');
const items = document.querySelectorAll('.item');
items.forEach(item => console.log(item.textContent));
Other packages similar to linkedom
jsdom
jsdom is a popular library that simulates a browser environment in Node.js. It provides a full-featured DOM and HTML parser, making it suitable for testing and server-side rendering. Compared to linkedom, jsdom is more comprehensive but also heavier and slower.
cheerio
Cheerio is a fast, flexible, and lean implementation of core jQuery designed specifically for the server. It parses HTML and XML documents and provides a jQuery-like API for DOM manipulation. Cheerio is lighter and faster than jsdom but does not support a full DOM environment like linkedom.
node-html-parser
node-html-parser is a fast HTML parser that can parse and manipulate HTML documents. It is lightweight and efficient but does not provide a full DOM API like linkedom. It is suitable for simple HTML parsing and manipulation tasks.