Parsing HTML
suggest changeParsing HTML on the server is an essential requirement for web scraping, metadata extraction, content sanitization, RSS feeds, and transforming legacy markup. Because Node.js does not provide a native browser DOM by default, developers use dedicated parsing libraries.
The most popular libraries for parsing HTML in Node.js are:
- Cheerio: A lightning-fast, lean implementation of jQuery core designed specifically for the server. It parses markup into an AST and provides familiar CSS selector syntax without the overhead of a full browser DOM.
- JSDOM: A full, standards-compliant JavaScript implementation of the WHATWG DOM and HTML standards, complete with
window,document, and support for running inline scripts. - node-html-parser: A minimalist, zero-dependency, high-performance HTML parser.
1. Fast HTML Parsing with Cheerio
Cheerio is the recommended tool for web scraping and static document analysis because it is orders of magnitude faster than a full DOM emulator.
Installation
npm install cheerio
Loading HTML and Querying with CSS Selectors
import * as cheerio from 'cheerio';
const html = `
<!DOCTYPE html>
<html>
<head><title>Tech Product Catalog</title></head>
<body>
<h1 class="header">Available Products</h1>
<ul id="product-list">
<li class="item" data-sku="SKU-001">
<span class="name">Mechanical Keyboard</span>
<span class="price">$120.00</span>
<a href="/products/mech-kb">Details</a>
</li>
<li class="item out-of-stock" data-sku="SKU-002">
<span class="name">Wireless Mouse</span>
<span class="price">$45.00</span>
<a href="/products/mouse">Details</a>
</li>
</ul>
</body>
</html>
`;
// Parse the HTML document
const $ = cheerio.load(html);
// Extract document title
const pageTitle = $('head title').text();
console.log('Title:', pageTitle);
// Query elements using CSS selectors
const products = [];
$('#product-list .item').each((index, element) => {
const item = $(element);
const name = item.find('.name').text().trim();
const price = item.find('.price').text().trim();
const sku = item.attr('data-sku');
const link = item.find('a').attr('href');
const isOutOfStock = item.hasClass('out-of-stock');
products.push({ sku, name, price, link, inStock: !isOutOfStock });
});
console.log('Parsed Products:', products);
2. Modifying and Generating HTML
Cheerio allows you to manipulate DOM nodes and output updated HTML:
import * as cheerio from 'cheerio';
const $ = cheerio.load('<div class="container"><p>Draft text</p></div>');
// Add classes and attributes
$('p').addClass('lead highlight').attr('id', 'intro');
// Append new elements
$('.container').append('<button type="button">Read More</button>');
// Serialize back to HTML string
const outputHtml = $.html();
console.log(outputHtml);
3. Full DOM Simulation with JSDOM
When you need browser APIs like document.createElement, Element.closest, TreeWalker, or need to evaluate client-side scripts, use JSDOM:
Installation
npm install jsdom
Querying with Standard Web APIs
import { JSDOM } from 'jsdom';
const htmlContent = `
<section id="reviews">
<div class="review" data-rating="5">Excellent service!</div>
<div class="review" data-rating="3">Average experience.</div>
</section>
`;
const dom = new JSDOM(htmlContent);
const document = dom.window.document;
// Use standard W3C DOM methods
const reviews = document.querySelectorAll('.review');
reviews.forEach((el) => {
console.log(`Rating: ${el.getAttribute('data-rating')} - Text: ${el.textContent}`);
});
4. Sanitizing Untrusted HTML
Never render or re-broadcast untrusted user-submitted HTML without sanitizing it to prevent Cross-Site Scripting (XSS) attacks. Use sanitize-html:
npm install sanitize-html
import sanitizeHtml from 'sanitize-html';
const dirtyHtml = `
<h3>User Bio</h3>
<script>alert('Stealing cookies!');</script>
<p>Hello world! Visit <a href="https://example.com" onclick="steal()">my site</a>.</p>
<img src="invalid" onerror="alert('xss')" />
`;
const cleanHtml = sanitizeHtml(dirtyHtml, {
allowedTags: ['h3', 'p', 'a', 'b', 'i', 'em', 'strong'],
allowedAttributes: {
a: ['href', 'title', 'target', 'rel'],
},
transformTags: {
a: sanitizeHtml.simpleTransform('a', { target: '_blank', rel: 'noopener noreferrer' }),
},
});
console.log(cleanHtml);
// Strips script tags, onerror attributes, and unauthorized tags
5. Summary & Choosing the Right Tool
| Tool | Primary Use Case | Performance | Script Execution |
|---|---|---|---|
| Cheerio | Fast server-side scraping & data extraction | Extremely Fast (AST parser) | No |
| JSDOM | Emulating browser environment & standard DOM | Moderate | Yes (Optional) |
| Puppeteer / Playwright | Single-page apps requiring full rendering (React, Vue) | Heavy (Real Chromium/WebKit instance) | Full Browser |