@dooboostore/dom-parser

中文文档
1.0.29发布于 2026/11/07MITTypeScriptESM + CJS近 30 天下载 3899

A lightweight DOM parser for server-side HTML parsing and manipulation with full DOM API support

原始使用文档
文档目录36 节
  1. Features
  2. Browser parity
  3. Installation
  4. Quick Start
  5. Basic HTML Parsing
  6. Quick Setup with parseHTML Utility
  7. Template Processing
  8. API Reference
  9. DomParser Class
  10. parseHTML Utility Function
  11. Supported DOM APIs
  12. Use Cases
  13. 🎯 HTML Processing & Manipulation
  14. 🔧 Server-Side Rendering (SSR)
  15. 📧 Email Template Processing
  16. 🌐 Web Scraping & Data Extraction
  17. 🎭 Custom Element Registration
  18. 🔍 Advanced DOM Traversal with TreeWalker
  19. 🎨 DOM Fragment Creation & Batch Operations
  20. 📋 HTML Validation & Cleanup
  21. 🚀 Advanced Features
  22. Document Reloading
  23. Memory Management
  24. Base URL Configuration
  25. CSS Selector Complexity
  26. Performance Characteristics
  27. DOM Node Classes Reference
  28. Core Classes
  29. DOM Node Classes
  30. Advanced Interfaces
  31. Comparison with Alternatives
  32. vs. JSDOM
  33. vs. Cheerio
  34. vs. Linked DOM
  35. Learn More
  36. License

@dooboostore/dom-parser

NPM version Build and Test License: MIT

A lightweight DOM parser for server-side HTML parsing and manipulation with full DOM API support. Every behavior below is verified against real Chromium — 292 tests, all green, no jsdom.


Features

  • ⚡ Server-Side DOM: Complete DOM implementation for Node.js environments with no third-party dependencies
  • 🔍 CSS Selector Support: Full querySelector and querySelectorAll with complex selectors support
  • 📦 Multi-Format: Available as ESM, CJS, and UMD bundles for maximum compatibility
  • 🛡️ TypeScript: Full TypeScript definitions included with JSDoc documentation
  • 🪶 Minimal Dependencies: Depends only on @dooboostore/core; lightweight and fast, suitable for serverless environments
  • 🎯 HTML Templates: Handles complex HTML templates, attributes, and custom elements
  • 🌳 DOM Traversal: Built-in support for TreeWalker and NodeIterator for efficient tree navigation
  • 🎭 Custom Elements: Full customElements.define() API for registering and using Web Components on the server
  • 📋 Standards Compliant: Implements standard DOM APIs (querySelector, appendChild, innerHTML, etc.)
  • 🧪 Browser Parity: Selector matching, IDL reflection, and serialization verified case-by-case against Chromium (see Browser parity below)
  • 🌑 Declarative Shadow DOM: getHTML() / setHTMLUnsafe() with declarative shadow root serialization for SSR pipelines
  • 💾 Memory Efficient: Proper garbage collection with destroy() method for long-running processes

Browser parity

Behavior is pinned against real Chromium (via Playwright), not against other emulators. Each item below is a passing test, not an aspiration:

  • Selectors: sibling axes (+, ~), :has() with anchor absolutization, explicit :scope binding to the query scope, absolute :is() / :where() / :not() contents inside :has(), :nth-child(an+b of S), of-filtered counting, attribute operators (=, ~=, |=, ^=, $=, *=, i modifier) including the empty-value rules ([a~=""], [a^=""], [a$=""], [a*=""] never match; [a|=""] keeps dash-list semantics)
  • IDL reflection: select.size / select.multiple, option.value / option.text (strip-and-collapse whitespace, script subtrees excluded), form.elements with spec form-owner association (form= attribute, no ancestor fallback on mismatch), control.form
  • Null handling: innerHTML / innerText / textContent setters clear on null and String()-coerce everything else, exactly like browsers
  • Serialization: SVG/MathML case preservation (<path>, not <PATH>), attribute escaping (&, <, >, non-breaking space), declarative shadow DOM round-trips

Installation

# pnpm
pnpm add @dooboostore/dom-parser

# npm
npm install @dooboostore/dom-parser

# yarn
yarn add @dooboostore/dom-parser

Quick Start

Basic HTML Parsing

import { DomParser } from '@dooboostore/dom-parser';

const html = `
<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
</head>
<body>
    <div id="app">
        <h1>Hello World</h1>
        <p class="content">This is a test paragraph.</p>
    </div>
</body>
</html>
`;

const parser = new DomParser(html);
const document = parser.document;

// Use standard DOM APIs
const title = document.querySelector('title');
console.log(title?.textContent); // "Test Page"

const app = document.getElementById('app');
console.log(app?.innerHTML); // Contains the div content

Quick Setup with parseHTML Utility

import { parseHTML } from '@dooboostore/dom-parser';

// Quick way to get window object for SSR
const window = parseHTML(html);
const document = window.document;

// Perfect for setting up global DOM
global.window = window;
global.document = document;

Template Processing

import { DomParser } from '@dooboostore/dom-parser';

// Parse HTML templates with complex attributes
const templateHtml = `
<div class="container">
    <button onclick="handleClick(data)" disabled="false">
        Click Me
    </button>
    <input value="user.name" placeholder="Enter name" />
</div>
`;

const parser = new DomParser(templateHtml);
const document = parser.document;

// Access and modify elements
const button = document.querySelector('button');
console.log(button?.getAttribute('onclick')); // "handleClick(data)"

const input = document.querySelector('input');
input?.setAttribute('value', 'new value');

API Reference

DomParser Class

Constructor

new DomParser(html: string, options?: DomParserOptions)

Creates a new DOM parser instance with the provided HTML string.

Parameters:

  • html: HTML string to parse
  • options: Optional configuration object

DomParserOptions:

interface DomParserOptions {
  href?: string;                              // Base URL for the document
  onUrlChange?: (url: string) => void;        // Called whenever the parsed document's `location.href` changes (e.g. from code running against the parsed DOM setting `location.href` or using history APIs)
  fetch?: typeof globalThis.fetch;             // Custom fetch implementation used by `window.fetch()` inside the parsed environment
}

Properties

  • document: Returns the parsed document object with full DOM API support
  • window: Returns the window object for server-side rendering compatibility

parseHTML Utility Function

Function Signature

parseHTML(html: string, options?: DomParserOptions): Window

A convenient utility function that creates a DomParser instance and returns the window object directly.

Usage:

import { parseHTML } from '@dooboostore/dom-parser';

// Quick setup for SSR
const window = parseHTML('<html><body><h1>Hello</h1></body></html>');
const document = window.document;

// Set up globals
global.window = window;
global.document = document;

// Use DOM APIs immediately
const h1 = document.querySelector('h1');
console.log(h1?.textContent); // "Hello"

Supported DOM APIs

  • document.querySelector() / document.querySelectorAll()
  • document.getElementById() / document.getElementsByClassName()
  • element.innerHTML / element.textContent
  • element.setAttribute() / element.getAttribute()
    • element.appendChild() / element.removeChild()
    • form.elements (spec form-owner association) / control.form
    • select.size / select.multiple, option.value / option.text
    • element.getHTML() / element.setHTMLUnsafe() (declarative shadow DOM)
  • document.createElement() / document.createTextNode()
  • document.createDocumentFragment()
  • NodeIterator / TreeWalker
  • CSS selector parsing with complex expressions
  • Event handling and DOM manipulation
  • Custom Element registration via customElements.define() (including customized built-ins via is="" and automatic upgrade of already-parsed elements)
  • Basic SVG (<svg>, <circle>, <rect>) and MathML element recognition alongside 70+ standard HTML element tags

Use Cases

🎯 HTML Processing & Manipulation

import { DomParser } from '@dooboostore/dom-parser';

function processHtml(html: string) {
    const parser = new DomParser(html);
    const document = parser.document;
    
    // Modify the DOM
    const title = document.querySelector('title');
    if (title) {
        title.textContent = 'Processed Title';
    }
    
    // Add meta tags
    const head = document.querySelector('head');
    const meta = document.createElement('meta');
    meta.setAttribute('name', 'description');
    meta.setAttribute('content', 'Processed content');
    head?.appendChild(meta);
    
    return document.documentElement.outerHTML;
}

🔧 Server-Side Rendering (SSR)

import { parseHTML } from '@dooboostore/dom-parser';

// Quick setup with parseHTML utility
const templateHtml = fs.readFileSync('template.html', 'utf8');
const window = parseHTML(templateHtml);

// Set up global DOM for SSR
global.document = window.document;
global.window = window;

// Now your components can use DOM APIs on the server

📧 Email Template Processing

import { DomParser } from '@dooboostore/dom-parser';

function generateEmailHtml(userData: {name: string, orderId: string}) {
    const templateHtml = `
    <html>
    <body>
        <h1>Hello <span class="user-name"></span>!</h1>
        <p>Your order <strong class="order-id"></strong> has been confirmed.</p>
    </body>
    </html>
    `;
    
    const parser = new DomParser(templateHtml);
    const document = parser.document;
    
    // Inject data into the template
    document.querySelector('.user-name')!.textContent = userData.name;
    document.querySelector('.order-id')!.textContent = userData.orderId;
    
    return document.documentElement.outerHTML;
}

🌐 Web Scraping & Data Extraction

import { DomParser } from '@dooboostore/dom-parser';
import { parseHTML } from '@dooboostore/dom-parser';

async function scrapeArticles(html: string) {
    const window = parseHTML(html);
    const document = window.document;
    
    const articles = [];
    const articleElements = document.querySelectorAll('article.post');
    
    articleElements.forEach(el => {
        const title = el.querySelector('h2')?.textContent || '';
        const author = el.querySelector('.author')?.textContent || '';
        const date = el.querySelector('.date')?.getAttribute('data-date') || '';
        
        articles.push({ title, author, date });
    });
    
    return articles;
}

🎭 Custom Element Registration

import { parseHTML } from '@dooboostore/dom-parser';

const window = parseHTML('<html><body></body></html>');

// Define a custom element (extend the parsed window's HTMLElement)
class MyCustomElement extends (window as any).HTMLElement {
    connectedCallback() {
        this.innerHTML = '<p>Custom Element Works!</p>';
    }
}

// Register custom element
window.customElements.define('my-element', MyCustomElement);

// Create and use custom element
const doc = window.document;
const customEl = doc.createElement('my-element');
doc.body?.appendChild(customEl);

console.log(doc.body?.outerHTML);
// <body><my-element><p>Custom Element Works!</p></my-element></body>

🔍 Advanced DOM Traversal with TreeWalker

import { parseHTML } from '@dooboostore/dom-parser';

const html = `
<div class="container">
    <h1>Title</h1>
    <section>
        <article>Item 1</article>
        <article>Item 2</article>
    </section>
</div>
`;

const window = parseHTML(html);
const document = window.document;

// Use TreeWalker for efficient traversal
const root = document.querySelector('.container');
const walker = document.createTreeWalker(
    root,
    window.NodeFilter.SHOW_ELEMENT,
    null
);

let node = walker.nextNode();
while (node) {
    console.log((node as Element).tagName, (node as Element).textContent);
    node = walker.nextNode();
}

🎨 DOM Fragment Creation & Batch Operations

import { parseHTML } from '@dooboostore/dom-parser';

const window = parseHTML('<html><body></body></html>');
const document = window.document;

// Create a document fragment for efficient batch operations
const fragment = document.createDocumentFragment();

for (let i = 1; i <= 5; i++) {
    const li = document.createElement('li');
    li.textContent = `Item ${i}`;
    fragment.appendChild(li);
}

const ul = document.createElement('ul');
ul.appendChild(fragment);
document.body?.appendChild(ul);

console.log(document.body?.outerHTML);
// Creates <ul> with 5 <li> items (fragment prevents multiple reflows)

📋 HTML Validation & Cleanup

import { DomParser } from '@dooboostore/dom-parser';

function sanitizeHtml(html: string): string {
    const parser = new DomParser(html);
    const document = parser.document;
    
    // Remove all scripts
    document.querySelectorAll('script').forEach(el => {
        el.parentNode?.removeChild(el);
    });
    
    // Remove event attributes
    const allElements = document.querySelectorAll('*');
    allElements.forEach(el => {
        Array.from(el.attributes || []).forEach(attr => {
            if (attr.name.startsWith('on')) {
                el.removeAttribute(attr.name);
            }
        });
    });
    
    return document.documentElement.outerHTML;
}

🚀 Advanced Features

Document Reloading

Update the parsed document with new HTML content without creating a new parser:

import { DomParser } from '@dooboostore/dom-parser';

const parser = new DomParser('<html><body><h1>Original</h1></body></html>');

// Later, load new HTML
parser.loadHTML('<html><body><h2>Updated</h2></body></html>');

const title = parser.document.querySelector('h2');
console.log(title?.textContent); // "Updated"

Memory Management

Properly clean up parser instances for long-running applications:

import { DomParser } from '@dooboostore/dom-parser';

const parser = new DomParser(largeHtml);

// Process document
const results = processDocument(parser.document);

// Destroy when done to free memory
parser.destroy();

Base URL Configuration

Set a base URL for relative URL resolution and API calls:

import { DomParser } from '@dooboostore/dom-parser';

const parser = new DomParser(html, {
    href: 'https://example.com/page/'
});

console.log(parser.window.location.href); // "https://example.com/page/"

CSS Selector Complexity

Supports complex CSS selectors for querying:

import { parseHTML } from '@dooboostore/dom-parser';

const html = `
<div class="container">
    <article class="featured">
        <h2>Title</h2>
        <p class="summary">Summary text</p>
    </article>
    <article>
        <h2>Another</h2>
    </article>
</div>
`;

const window = parseHTML(html);
const doc = window.document;

// Complex selectors
const featured = doc.querySelector('article.featured > p.summary');
const allHeadings = doc.querySelectorAll('article > h2');
const byAttribute = doc.querySelectorAll('[class~="featured"]');

console.log(featured?.textContent); // "Summary text"
console.log(allHeadings.length); // 2

Performance Characteristics

Measured on a reference run (Node 24, Apple Silicon, 500-element document, median of 21 runs):

  • Parse: ~3.7 ms — same rig: linkedom ~5.0 ms, jsdom ~20 ms
  • Serialize (outerHTML): ~1.1 ms
  • querySelectorAll: ~0.3 ms cached; cold unique selectors pay compile cost once, then cache
  • No Third-Party Dependencies: No jsdom, cheerio, or other heavyweight parsers — only @dooboostore/core
  • Lightweight: Suitable for microservices and serverless environments
  • Memory Efficient: Clean separation of concerns with proper garbage collection
  • TreeWalker & NodeIterator: Efficient DOM traversal without loading entire tree into memory

DOM Node Classes Reference

Core Classes

DomParser

Main class for parsing HTML strings and creating DOM environments.

// Constructor
new DomParser(html: string, options?: DomParserOptions)

// Methods
get document(): Document              // Access the parsed document
get window(): Window                  // Access the window object
loadHTML(html: string): void          // Clear head/body and parse new HTML into the same document
parseHTML(html: string): void         // Parse HTML into the current document (used by the constructor)
destroy(): void                       // Destroy parser and free memory

// Options
interface DomParserOptions {
  href?: string;                          // Base URL for the document
  onUrlChange?: (url: string) => void;    // Fires when the parsed document's location.href changes
  fetch?: typeof globalThis.fetch;        // Custom fetch implementation for window.fetch()
}

parseHTML Utility

Quick utility function for SSR setup:

const window = parseHTML(html, options?: DomParserOptions);
// Returns Window object directly
// window.document available immediately

DOM Node Classes

The package provides TypeScript implementations of standard DOM interfaces. Exported from the root:

  • WindowBase: The window implementation (location, history, navigator, customElements, fetch, DOM constructors)
  • DocumentBase: Full Document implementation with querySelector, getElementById, createElement, etc.
  • NodeBase / ElementBase / HTMLElementBase: Node, element (attribute management) and HTML element base classes
  • HTMLElement: Standard HTML element class
  • DocumentFragmentBase: Document fragments for batch operations
  • ShadowRootBase: Shadow DOM support
  • ElementFactory: Static createElement(tagName, ownerDocument?) plus getSupportedTagNames() (and HTML/SVG/MathML variants)

Text nodes (TextBase) and comments (Comment) are implemented internally and created via document.createTextNode() / createComment().

Advanced Interfaces

// Importable from '@dooboostore/dom-parser'
NodeIterator     // Traverse DOM nodes sequentially (also returned by document.createNodeIterator())
NodeFilter       // Node-filtering constants (SHOW_ELEMENT, SHOW_TEXT, ...)
ParentNodeBase   // Base class implementing child-node management
ChildNodeBase    // Base class implementing parent/sibling navigation

// Not a top-level export — obtained via document.createTreeWalker(), not imported directly
TreeWalker       // Efficient DOM tree traversal with filters

Comparison with Alternatives

vs. JSDOM

  • dom-parser: Lightweight, zero third-party dependencies, single-purpose; parses the reference 500-element document in ~3.7 ms
  • jsdom: Full browser simulation, larger bundle, more overhead (~20 ms on the same document)

vs. Cheerio

  • dom-parser: Pure DOM API compatibility (querySelector, form.elements, IDL reflection), TypeScript, no jQuery wrapper needed
  • cheerio: jQuery API syntax, familiar for jQuery users

vs. Linked DOM

  • dom-parser: Simpler core, focused on HTML parsing
  • Linked DOM: More comprehensive library-level ecosystem

Learn More

The detailed API documentation, including all supported DOM methods and usage examples, is available on our documentation website.

License

This package is licensed under the MIT License.

版本与发布记录

@dooboostore/dom-parser 共发布 30 个版本,首次发布于 2025/10/09;过去 12 个月发布了 28 个版本。

版本发布日期距今
1.0.29latest2026/11/076 天前
1.0.282026/11/076 天前
1.0.272026/11/076 天前
1.0.262026/11/076 天前
1.0.252026/11/0112 天前
1.0.242026/11/0112 天前

关于 @dooboostore/dom-parser 的常见问题

@dooboostore/dom-parser 是什么?

A lightweight DOM parser for server-side HTML parsing and manipulation with full DOM API support

如何安装 @dooboostore/dom-parser?

在项目目录运行 npm install @dooboostore/dom-parser,或使用 pnpm add / yarn add / bun add。

@dooboostore/dom-parser 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dooboostore/dom-parser 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@dooboostore/dom-parser 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dooboostore/dom-parser 可以商用吗?

@dooboostore/dom-parser 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dooboostore/dom-parser 的下载量有多少?

根据 npm 官方下载统计,@dooboostore/dom-parser 在 2026/10/13 – 2026/11/11 这 30 天内被下载 3,899 次,日均约 130 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dooboostore/dom-parser 还在维护吗?

最新版本 1.0.29 发布于 2026/11/07(6 天前);至今共发布 30 个版本,其中过去 12 个月发布了 28 个;首次发布于 2025/10/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。