A lightweight DOM parser for server-side HTML parsing and manipulation with full DOM API support.
querySelectorandquerySelectorAllwith complex selectors support@dooboostore/core; lightweight and fast, suitable for serverless environmentsTreeWalkerandNodeIteratorfor efficient tree navigationcustomElements.define()API for registering and using Web Components on the serverdestroy()method for long-running processes# pnpmpnpm add @dooboostore/dom-parser# npmnpm install @dooboostore/dom-parser# yarnyarn add @dooboostore/dom-parserimport{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 contentimport{ 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;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');newDomParser(html:string,options?:DomParserOptions)Creates a new DOM parser instance with the provided HTML string.
Parameters:
html: HTML string to parseoptions: Optional configuration objectDomParserOptions:
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}document: Returns the parsed document object with full DOM API supportwindow: Returns the window object for server-side rendering compatibilityparseHTML(html:string,options?:DomParserOptions):WindowA 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"document.querySelector()/document.querySelectorAll()document.getElementById()/document.getElementsByClassName()element.innerHTML/element.textContentelement.setAttribute()/element.getAttribute()element.appendChild()/element.removeChild()document.createElement()/document.createTextNode()document.createDocumentFragment()NodeIterator/TreeWalkercustomElements.define()(including customized built-ins viais=""and automatic upgrade of already-parsed elements)<svg>,<circle>,<rect>) and MathML element recognition alongside 70+ standard HTML element tagsimport{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;
}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 serverimport{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;
}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;
}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>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();
}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)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;
}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"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();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/"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);// 2Main 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()}Quick utility function for SSR setup:
constwindow=parseHTML(html,options?:DomParserOptions);// Returns Window object directly// window.document available immediatelyThe package provides TypeScript implementations of standard DOM interfaces. Exported from the root:
windowimplementation (location, history, navigator,customElements,fetch, DOM constructors)querySelector,getElementById,createElement, etc.createElement(tagName, ownerDocument?)plusgetSupportedTagNames()(and HTML/SVG/MathML variants)Text nodes (TextBase) and comments (Comment) are implemented internally and created viadocument.createTextNode()/createComment().
// 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 filtersThe detailed API documentation, including all supported DOM methods and usage examples, is available on our documentation website.
This package is licensed under theMIT License.