@dooboostore/dom-parser

NPM versionBuild and TestLicense: MIT

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


Features

  • ⚡ Server-Side DOM: Complete DOM implementation for Node.js environments with no third-party dependencies
  • 🔍 CSS Selector Support: FullquerySelectorandquerySelectorAllwith 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 forTreeWalkerandNodeIteratorfor efficient tree navigation
  • 🎭 Custom Elements: FullcustomElements.define()API for registering and using Web Components on the server
  • 📋 Standards Compliant: Implements standard DOM APIs (querySelector, appendChild, innerHTML, etc.)
  • 💾 Memory Efficient: Proper garbage collection withdestroy()method for long-running processes

Installation

# pnpmpnpm add @dooboostore/dom-parser# npmnpm install @dooboostore/dom-parser# yarnyarn add @dooboostore/dom-parser

Quick Start

Basic HTML Parsing

import{DomParser}from'@dooboostore/dom-parser';consthtml =`
<!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>
`;constparser =newDomParser(html);constdocument= parser.document;// Use standard DOM APIsconsttitle =document.querySelector('title');console.log(title?.textContent);// "Test Page"constapp =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 SSRconstwindow=parseHTML(html);constdocument=window.document;// Perfect for setting up global DOMglobal.window=window;global.document=document;

Template Processing

import{DomParser}from'@dooboostore/dom-parser';// Parse HTML templates with complex attributesconsttemplateHtml =`
<div class="container">
    <button onclick="handleClick(data)" disabled="false">
        Click Me
    </button>
    <input value="user.name" placeholder="Enter name" />
</div>
`;constparser =newDomParser(templateHtml);constdocument= parser.document;// Access and modify elementsconstbutton =document.querySelector('button');console.log(button?.getAttribute('onclick'));// "handleClick(data)"constinput =document.querySelector('input');
input?.setAttribute('value','new value');

API Reference

DomParser Class

Constructor

newDomParser(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:

interfaceDomParserOptions{href?:string;// Base URL for the documentonUrlChange?:(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?:typeofglobalThis.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 SSRconstwindow=parseHTML('<html><body><h1>Hello</h1></body></html>');constdocument=window.document;// Set up globalsglobal.window=window;global.document=document;// Use DOM APIs immediatelyconsth1 =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()
  • document.createElement()/document.createTextNode()
  • document.createDocumentFragment()
  • NodeIterator/TreeWalker
  • CSS selector parsing with complex expressions
  • Event handling and DOM manipulation
  • Custom Element registration viacustomElements.define()(including customized built-ins viais=""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';functionprocessHtml(html:string) {constparser =newDomParser(html);constdocument= parser.document;// Modify the DOMconsttitle =document.querySelector('title');if(title) {
        title.textContent='Processed Title';
    }// Add meta tagsconsthead =document.querySelector('head');constmeta =document.createElement('meta');
    meta.setAttribute('name','description');
    meta.setAttribute('content','Processed content');
    head?.appendChild(meta);returndocument.documentElement.outerHTML;
}

🔧 Server-Side Rendering (SSR)

import{ parseHTML }from'@dooboostore/dom-parser';// Quick setup with parseHTML utilityconsttemplateHtml = fs.readFileSync('template.html','utf8');constwindow=parseHTML(templateHtml);// Set up global DOM for SSRglobal.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';functiongenerateEmailHtml(userData: {name:string, orderId:string}) {consttemplateHtml =`
    <html>
    <body>
        <h1>Hello <span class="user-name"></span>!</h1>
        <p>Your order <strong class="order-id"></strong> has been confirmed.</p>
    </body>
    </html>
    `;constparser =newDomParser(templateHtml);constdocument= parser.document;// Inject data into the templatedocument.querySelector('.user-name')!.textContent= userData.name;document.querySelector('.order-id')!.textContent= userData.orderId;returndocument.documentElement.outerHTML;
}

🌐 Web Scraping & Data Extraction

import{DomParser}from'@dooboostore/dom-parser';import{ parseHTML }from'@dooboostore/dom-parser';asyncfunctionscrapeArticles(html:string) {constwindow=parseHTML(html);constdocument=window.document;constarticles = [];constarticleElements =document.querySelectorAll('article.post');
    
    articleElements.forEach(el=>{consttitle = el.querySelector('h2')?.textContent||'';constauthor = el.querySelector('.author')?.textContent||'';constdate = el.querySelector('.date')?.getAttribute('data-date') ||'';
        
        articles.push({ title, author, date });
    });returnarticles;
}

🎭 Custom Element Registration

import{ parseHTML }from'@dooboostore/dom-parser';constwindow=parseHTML('<html><body></body></html>');// Define a custom element (extend the parsed window's HTMLElement)classMyCustomElementextends(windowasany).HTMLElement{connectedCallback() {this.innerHTML='<p>Custom Element Works!</p>';
    }
}// Register custom elementwindow.customElements.define('my-element',MyCustomElement);// Create and use custom elementconstdoc =window.document;constcustomEl = 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';consthtml =`
<div class="container">
    <h1>Title</h1>
    <section>
        <article>Item 1</article>
        <article>Item 2</article>
    </section>
</div>
`;constwindow=parseHTML(html);constdocument=window.document;// Use TreeWalker for efficient traversalconstroot =document.querySelector('.container');constwalker =document.createTreeWalker(
    root,window.NodeFilter.SHOW_ELEMENT,null);letnode = walker.nextNode();while(node) {console.log((nodeasElement).tagName, (nodeasElement).textContent);
    node = walker.nextNode();
}

🎨 DOM Fragment Creation & Batch Operations

import{ parseHTML }from'@dooboostore/dom-parser';constwindow=parseHTML('<html><body></body></html>');constdocument=window.document;// Create a document fragment for efficient batch operationsconstfragment =document.createDocumentFragment();for(leti =1; i <=5; i++) {constli =document.createElement('li');
    li.textContent=`Item${i}`;
    fragment.appendChild(li);
}constul =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';functionsanitizeHtml(html:string):string{constparser =newDomParser(html);constdocument= parser.document;// Remove all scriptsdocument.querySelectorAll('script').forEach(el=>{
        el.parentNode?.removeChild(el);
    });// Remove event attributesconstallElements =document.querySelectorAll('*');
    allElements.forEach(el=>{Array.from(el.attributes|| []).forEach(attr=>{if(attr.name.startsWith('on')) {
                el.removeAttribute(attr.name);
            }
        });
    });returndocument.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';constparser =newDomParser('<html><body><h1>Original</h1></body></html>');// Later, load new HTMLparser.loadHTML('<html><body><h2>Updated</h2></body></html>');consttitle = 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';constparser =newDomParser(largeHtml);// Process documentconstresults =processDocument(parser.document);// Destroy when done to free memoryparser.destroy();

Base URL Configuration

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

import{DomParser}from'@dooboostore/dom-parser';constparser =newDomParser(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';consthtml =`
<div class="container">
    <article class="featured">
        <h2>Title</h2>
        <p class="summary">Summary text</p>
    </article>
    <article>
        <h2>Another</h2>
    </article>
</div>
`;constwindow=parseHTML(html);constdoc =window.document;// Complex selectorsconstfeatured = doc.querySelector('article.featured > p.summary');constallHeadings = doc.querySelectorAll('article > h2');constbyAttribute = doc.querySelectorAll('[class~="featured"]');console.log(featured?.textContent);// "Summary text"console.log(allHeadings.length);// 2

Performance Characteristics

  • No Third-Party Dependencies: No jsdom, cheerio, or other heavyweight parsers
  • Lightweight: Suitable for microservices and serverless environments
  • Fast Parsing: Optimized HTML parsing algorithm
  • 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.

// ConstructornewDomParser(html:string,options?:DomParserOptions)// Methodsgetdocument():Document// Access the parsed documentgetwindow():Window// Access the window objectloadHTML(html:string):void// Clear head/body and parse new HTML into the same documentparseHTML(html:string):void// Parse HTML into the current document (used by the constructor)destroy():void// Destroy parser and free memory// OptionsinterfaceDomParserOptions{href?:string;// Base URL for the documentonUrlChange?:(url:string) =>void;// Fires when the parsed document's location.href changesfetch?:typeofglobalThis.fetch;// Custom fetch implementation for window.fetch()}

parseHTML Utility

Quick utility function for SSR setup:

constwindow=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: Thewindowimplementation (location, history, navigator,customElements,fetch, DOM constructors)
  • DocumentBase: Full Document implementation withquerySelector,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: StaticcreateElement(tagName, ownerDocument?)plusgetSupportedTagNames()(and HTML/SVG/MathML variants)

Text nodes (TextBase) and comments (Comment) are implemented internally and created viadocument.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 managementChildNodeBase// Base class implementing parent/sibling navigation// Not a top-level export — obtained via document.createTreeWalker(), not imported directlyTreeWalker// Efficient DOM tree traversal with filters

Comparison with Alternatives

vs. JSDOM

  • dom-parser: Lightweight, zero dependencies, single-purpose
  • jsdom: Full browser simulation, larger bundle, more overhead

vs. Cheerio

  • dom-parser: Pure DOM API compatibility, 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 theMIT License.