### Install via npm Source: https://github.com/beforesemicolon/html-parser/blob/master/README.md Install the package from npm for Node.js projects. ```bash npm install @beforesemicolon/html-parser ``` -------------------------------- ### Include via CDN script tags Source: https://github.com/beforesemicolon/html-parser/blob/master/README.md Load the parser in the browser via a CDN, either the latest version or a pinned version (1.0.0 in this example). ```html ``` -------------------------------- ### Custom handler implementation example Source: https://github.com/beforesemicolon/html-parser/blob/master/README.md Create a custom handler object with createComment, createTextNode, createDocumentFragment, and createElementNS methods to transform HTML into any structure. Ensure namespaceURI is always included in the element object. ```ts const MyCustomDoc = { createComment: (value: string) => ({type: 'comment', value}), createTextNode: (value: string) => ({type: 'text', value}), createDocumentFragment: () => { const children: unknown[] = [] return { type: 'fragment', children, appendChild: (node: unknown) => { children.push(node) } } }, createElementNS: (namespaceURI: string, tagName: string) => { const children: unknown[] = [] const attributes: Record = {} return { namespaceURI, // important to ALWAYS include tagName, children, attributes, type: 'node', appendChild(node: unknown) { children.push(node) }, setAttribute(name: string, value: string) { attributes[name] = value; } } }, } const result = parse(`...`, MyCustomDoc); ``` -------------------------------- ### Streaming with a callback Source: https://github.com/beforesemicolon/html-parser Uses a NodeHandlerCallback to process nodes as they are parsed. The callback receives nodes of type element (1), text (3), or comment (8); the example logs text and comment values and collects element tag names. ```TypeScript import { parse, type NodeHandlerCallback } from '@beforesemicolon/html-parser' const seen: Array = [] const onNode: NodeHandlerCallback = (node) => { if (node.nodeType === 1) seen.push((node as ElementLike).tagName) // element if (node.nodeType === 3) console.log('text:', node.nodeValue) // text if (node.nodeType === 8) console.log('comment:', node.nodeValue) // comment } const frag = parse('

Hello world

', onNode) // logs: text: 'Hello', comment: ' note ', text: 'world' // seen: ['P'] ``` -------------------------------- ### NamedNodeMapLike Source: https://github.com/beforesemicolon/html-parser An interface representing a collection of attributes. Provides methods to get, set, remove, and iterate over attributes by name or index. ```APIDOC ## NamedNodeMapLike ### Description An interface representing a collection of attributes. Provides methods to get, set, remove, and iterate over attributes by name or index. ### Methods #### getNamedItem(name: string): AttrLike | null Look up an attribute by name. #### setNamedItem(attr: AttrLike): AttrLike Insert an attribute; same name overwrites; returns the stored attribute. #### removeNamedItem(name: string): AttrLike | null Delete an attribute by name and return it, or null if not found. #### item(index: number): AttrLike | null Access an attribute by index (insertion order). ### Properties - **length** (number) - Attribute count. ### Iteration - **[Symbol.iterator]()** - Iterable in insertion order. ### Exposed As - `ElementLike.attributes` ``` -------------------------------- ### Building a document manually with Doc Source: https://github.com/beforesemicolon/html-parser Creates a document fragment, an XHTML h1 element, and a text node, then appends them. After appending, h1.textContent returns 'Hello' and h1.outerHTML returns '

Hello

'. ```TypeScript import { Doc } from '@beforesemicolon/html-parser' const frag = Doc.createDocumentFragment() const h1 = Doc.createElementNS('http://www.w3.org/1999/xhtml', 'h1') h1.appendChild(Doc.createTextNode('Hello')) frag.appendChild(h1) h1.textContent // 'Hello' h1.outerHTML // '

Hello

' ``` -------------------------------- ### createTextNode Source: https://github.com/beforesemicolon/html-parser Creates a text node with the given text content. Returns a Text instance with nodeType 3 and nodeName '#text'. ```APIDOC ## createTextNode ### Description Creates a text node with the given text content. Returns a Text instance with nodeType 3 and nodeName '#text'. ### Method createTextNode ### Parameters - `nodeValue` (string) - Optional - The text content of the node. Defaults to `''`. ### Returns TextLike - A Text instance with nodeType 3, nodeName '#text', and nodeValue set to the provided string. ``` -------------------------------- ### Benchmark parse (default) Source: https://github.com/beforesemicolon/html-parser/blob/master/README.md Benchmark parse without a Document, showing an average duration of about 1.86 ms per file. ```ts import {parse} from "@beforesemicolon/html-parser"; parse(aReallyMassimeHTMLString); // avg duration: 1.86113 ms/file ± 1.09698 ``` -------------------------------- ### createElementNS Source: https://github.com/beforesemicolon/html-parser Creates an Element with the given namespace and tag name. The tag name is uppercased on the returned element. Returns an ElementLike instance with nodeType 1. ```APIDOC ## createElementNS ### Description Creates an Element with the given namespace and tag name. The tag name is uppercased on the returned element. Returns an ElementLike instance with nodeType 1. ### Method createElementNS ### Parameters - `ns` (string) - Required - Namespace URI stored as `namespaceURI`. - `name` (string) - Required - Tag name; uppercased on the returned element. ### Returns ElementLike - An Element instance with nodeType 1, tagName/nodeName set to the uppercased name, and empty children, childNodes, and attributes map. ``` -------------------------------- ### Handle nodes with callback option Source: https://github.com/beforesemicolon/html-parser/blob/master/README.md Parse using a callback as the second parameter to handle each node as it is created. The callback receives DOM nodes and elements because the default document is used. ```js const frag = parse('

site title

', (node) => { // handle node here }); ``` -------------------------------- ### Custom DocumentLike handler with parse() Source: https://github.com/beforesemicolon/html-parser Defines a tracker implementing the four DocumentLike methods (createTextNode, createComment, createDocumentFragment, createElementNS) and passes it to parse(). Every parser-produced node goes through these methods. The output shows that text nodes are childNodes, not children, so frag.children[0].children.length is 0. ```TypeScript import { parse, type DocumentLike, type ElementLike } from '@beforesemicolon/html-parser' const tracker: DocumentLike = { createTextNode: (value) => ({ nodeType: 3, nodeName: '#text', nodeValue: value }), createComment: (value) => ({ nodeType: 8, nodeName: '#comment', nodeValue: value }), createDocumentFragment: () => ({ nodeType: 11, nodeName: '#fragment', nodeValue: null, tagName: '#fragment', childNodes: [], children: [], textContent: '', appendChild(node: unknown) { this.childNodes.push(node as never) }, } as never), createElementNS: (namespaceURI, tagName) => ({ nodeType: 1, nodeName: tagName, nodeValue: null, tagName, namespaceURI, childNodes: [], children: [], textContent: '', attributes: { getNamedItem: () => null, setNamedItem: (a) => a, removeNamedItem: () => null, item: () => null, length: 0, [Symbol.iterator]: () => [][Symbol.iterator]() }, outerHTML: '', setAttribute() {}, appendChild(node: unknown) { this.childNodes.push(node as never) }, } as never as ElementLike), } const frag = parse('

hi

', tracker) console.log(frag.children[0].children.length) // 0 (text is a childNode, not a child) ``` -------------------------------- ### Use in browser via global object Source: https://github.com/beforesemicolon/html-parser/blob/master/README.md Browser usage with the global window.BFS object, showing both default and native DOM Document parsing. ```html ``` -------------------------------- ### createComment Source: https://github.com/beforesemicolon/html-parser Creates a comment node with the given comment body. Returns a Comment instance with nodeType 8 and nodeName '#comment'. ```APIDOC ## createComment ### Description Creates a comment node with the given comment body. Returns a Comment instance with nodeType 8 and nodeName '#comment'. ### Method createComment ### Parameters - `nodeValue` (string) - Optional - The comment body (without ``). Defaults to `''`. ### Returns CommentLike - A Comment instance with nodeType 8 and nodeName '#comment'. ``` -------------------------------- ### createDocumentFragment Source: https://github.com/beforesemicolon/html-parser Creates a DocumentFragment rooted at the XHTML namespace with internal tag name '#fragment'. Returns a DocumentFragmentLike instance with nodeType 11. ```APIDOC ## createDocumentFragment ### Description Creates a DocumentFragment rooted at the XHTML namespace with internal tag name '#fragment'. Returns a DocumentFragmentLike instance with nodeType 11. ### Method createDocumentFragment ### Parameters None ### Returns DocumentFragmentLike - A DocumentFragment instance with nodeType 11, namespaceURI 'http://www.w3.org/1999/xhtml', and tag name '#fragment'. ``` -------------------------------- ### parse() Source: https://github.com/beforesemicolon/html-parser Parses an HTML string into a document fragment. Returns a DocumentFragmentLike or standard DocumentFragment depending on the document type. Never throws; malformed markup degrades to text nodes. ```APIDOC ## parse() ### Description Parses an HTML string into a document fragment. Returns a DocumentFragmentLike or standard DocumentFragment depending on the document type. Never throws; malformed markup degrades to text nodes. ### Return Value - `DocumentFragmentLike` (when `D` satisfies `DocumentLike`, including the default `Doc`). - `DocumentFragment` (the standard DOM type, when a real `Document` is passed). - The fragment's `children` holds top-level elements; `childNodes` holds every top-level node including text and comments. ### Behavior - **No `<` in input** — the entire string becomes a single text node. - **Whitespace preserved** — all whitespace between tags is kept as text nodes. - **Comments** (``) — created via `doc.createComment(...)`; an unterminated comment falls back to text. - **Declarations and processing instructions** (`` — are parsed and then **discarded**; the surrounding text is kept. Unterminated ones are kept as text. - **Void elements** (no closing tag): `AREA, BASE, BR, COL, COMMAND, EMBED, HR, IMG, INPUT, KEYGEN, LINK, MENUITEM, META, PARAM, SOURCE, TRACK, WBR` — any of these, or any tag ending in `/`, is not pushed onto the open-tag stack. - **Raw-text elements** — `STYLE`, `TEXTAREA`, `TITLE`, and `SCRIPT` — their content is captured with `findRawTextEnd`; only `SCRIPT` counts nested opening tags. Content inside `SCRIPT` is appended as a text node **without** notifying the callback; other raw-text content does notify. - **Closing tags** — pop the stack down to the nearest matching open tag; comparison is case-insensitive. A closing tag with no matching open tag is ignored. - **Unclosed tags** — the stack is never force-closed inside the loop, so trailing text of an unclosed element ends up inside it; mismatched closers close the matching ancestor. - **Legacy attribute placeholders** — attribute names matching `/^\$val[0-9]+["']?$/` (e.g. `$val0`, `$val0"`) are normalized: leading `$` and a trailing quote are stripped. This is a compatibility shim for markup generators. - **Navigation error tolerance** — angle brackets inside quoted attribute values do not end the tag. Unquoted attribute values end at whitespace or a trailing `/`. - **Namespaces** — `SVG` → `http://www.w3.org/2000/svg`, `MATH` → `http://www.w3.org/1998/Math/MathML`, `HTML` → `http://www.w3.org/1999/xhtml`; otherwise the parent's `namespaceURI`, except children of an SVG `foreignObject` fall back to the HTML namespace. - **Callback timing** — the callback fires with each created node: text nodes (except `SCRIPT` inner text), comment nodes, and element nodes **at creation time** (before their children are parsed). - **Reentrancy** — no module-level mutable state; starting a nested `parse` from inside a callback does not corrupt the outer parse. - **Errors** — the function never throws. Malformed markup (unterminated comments/declarations/tags) degrades to text nodes. There is no error type to catch. ``` -------------------------------- ### Module entry re-exports Source: https://github.com/beforesemicolon/html-parser The module entry point re-exports the public API from parse.ts and Doc.ts. ```TypeScript export * from './parse.ts' export * from './Doc.ts' ``` -------------------------------- ### Basic parse in a non-DOM environment Source: https://github.com/beforesemicolon/html-parser/blob/master/README.md Basic usage in environments without a DOM (e.g., Node) that returns a DocumentFragment-like object by default. ```js import {parse} from "@beforesemicolon/html-parser"; const frag = parse('

site title

'); // return DocumentFragment-like object frag.children[0] // h1 Element ``` -------------------------------- ### parse(markup, handler?) Source: https://github.com/beforesemicolon/html-parser Parses an HTML string into a document fragment (or equivalent object from a custom DocumentLike handler). Optionally streams every created node through a callback. ```APIDOC ## parse(markup, handler?) ### Description Parses an HTML string into a document fragment (or equivalent object from a custom DocumentLike handler). Optionally streams every created node through a callback. ### Method Function call ### Endpoint `parse(markup: string, handler?: D | NodeHandlerCallback): ParseReturn` ### Parameters #### Function Parameters - **markup** (string) - Required - The HTML source to parse. - **handler** (D | NodeHandlerCallback) - Optional - Either a DocumentLike duck-typed factory (the built-in Doc, a real DOM Document from browser/jsdom, or a custom handler), or a callback invoked for every created node. Defaults to `Doc as D`. ### Response #### Success Response Returns a `DocumentFragmentLike` if the handler satisfies `DocumentLike`, otherwise a standard DOM `DocumentFragment`. ### Type Definitions ```ts type ParseReturn = T extends DocumentLike ? DocumentFragmentLike : DocumentFragment export type NodeHandlerCallback = (node: ElementLike | NodeLike) => void ``` ``` -------------------------------- ### Using a real DOM Document (browser or jsdom) Source: https://github.com/beforesemicolon/html-parser Passes a real DOM Document (e.g., from jsdom) as the second argument to parse, returning a standard DocumentFragment. Requires the jsdom package. ```TypeScript import { parse } from '@beforesemicolon/html-parser' import { JSDOM } from 'jsdom' const document = new JSDOM('').window.document const frag = parse('

site title

', document) // standard DocumentFragment frag.children[0].tagName // 'H1' ``` -------------------------------- ### Benchmark parse with jsdom Document Source: https://github.com/beforesemicolon/html-parser/blob/master/README.md Benchmark parse using jsdom's Document, with an average duration of about 27.36 ms per file. ```ts import * as jsdom from "jsdom"; import {parse} from "@beforesemicolon/html-parser"; const {JSDOM} = jsdom; const document = new JSDOM('').window.document; parse(aReallyMassimeHTMLString, document); // avg duration: 27.3563 ms/file ± 19.1060` ``` -------------------------------- ### Manipulating a parsed fragment Source: https://github.com/beforesemicolon/html-parser Parses an HTML string, then modifies the first child element by setting an attribute, updating textContent, and appending a comment. The resulting outerHTML shows the updated attribute and text plus the comment. ```TypeScript import { parse } from '@beforesemicolon/html-parser' const frag = parse('
x
') const div = frag.children[0] div.setAttribute('data-id', '42') div.textContent = 'updated' // sets the internal nodeValue div.appendChild(Doc.createComment('note')) div.outerHTML // '
updated
' ``` -------------------------------- ### Use with jsdom Document in Node Source: https://github.com/beforesemicolon/html-parser/blob/master/README.md Parse in a DOM-like environment by providing a Document object (e.g., from jsdom) as the second argument to parse. ```js import * as jsdom from "jsdom"; const {JSDOM} = jsdom; const document = new JSDOM('').window.document; // import the parser import {parse} from "@beforesemicolon/html-parser"; const frag = parse('

site title

', document); // return DocumentFragment frag.children[0] // h1 Element ``` -------------------------------- ### Basic usage with built-in Doc Source: https://github.com/beforesemicolon/html-parser Parses an HTML string into a DocumentFragment-like object using the built-in Doc. The returned fragment's children are ElementLike nodes with tagName in uppercase; attributes are accessible via getNamedItem. ```TypeScript import { parse } from '@beforesemicolon/html-parser' const frag = parse('

site title

') const main = frag.children[0] // ElementLike, tagName 'MAIN' const h1 = main.children[0] // ElementLike, tagName 'H1' h1.textContent // 'site title' h1.attributes.getNamedItem('class')?.value // 'title' h1.outerHTML // '

site title

' ``` -------------------------------- ### Error-tolerant handling of malformed input Source: https://github.com/beforesemicolon/html-parser Shows that parse never throws on malformed input; an unterminated declaration is treated as text content. ```TypeScript import { parse } from '@beforesemicolon/html-parser' // never throws: const frag = parse('
before text frag.textContent // 'before Doc.createTextNode(value), createComment: (value) => Doc.createComment(value), createDocumentFragment: () => Doc.createDocumentFragment(), createElementNS: (ns, name) => { const el = Doc.createElementNS(ns, name) // decorate the element before parse appends to it return el }, } const frag = parse('

hi

', wrappingDoc) ``` -------------------------------- ### Doc factory implementation (src/Doc.ts:281) Source: https://github.com/beforesemicolon/html-parser Default node factory used by parse; creates plain class-backed nodes without a DOM. The four methods are the complete public surface; backing classes are not exported. ```TypeScript // src/Doc.ts:281 export const Doc: DocumentLike = { createTextNode: (nodeValue = '') => new Text(nodeValue), createComment: (nodeValue = '') => new Comment(nodeValue), createDocumentFragment: () => new DocumentFragment('http://www.w3.org/1999/xhtml', '#fragment'), createElementNS: (ns: string, name: string) => new Element(ns, name.toUpperCase()), } ``` -------------------------------- ### Custom handler (transform HTML into your own model) Source: https://github.com/beforesemicolon/html-parser Defines a custom handler object with createComment, createTextNode, createDocumentFragment, createElementNS, and appendChild/setAttribute methods. The parse function is generic over the handler; the result's fragment type matches the handler's createDocumentFragment return type. ```TypeScript import { parse } from '@beforesemicolon/html-parser' const MyCustomDoc = { createComment: (value: string) => ({ type: 'comment', value }), createTextNode: (value: string) => ({ type: 'text', value }), createDocumentFragment: () => { const children: unknown[] = [] return { type: 'fragment', children, appendChild: (node: unknown) => { children.push(node) }, } }, createElementNS: (namespaceURI: string, tagName: string) => { const children: unknown[] = [] const attributes: Record = {} return { namespaceURI, // required for namespace propagation tagName, children, attributes, type: 'node', appendChild(node: unknown) { children.push(node) }, setAttribute(name: string, value: string) { attributes[name] = value }, } }, } const model = parse('
  • A
  • B
', MyCustomDoc) // model.type === 'fragment'; model.children[0].children.length === 2 ``` -------------------------------- ### ElementLike Source: https://github.com/beforesemicolon/html-parser An interface representing an HTML or XML element. Provides properties and methods to access and manipulate element attributes, children, and text content. ```APIDOC ## ElementLike ### Description An interface representing an HTML or XML element. Provides properties and methods to access and manipulate element attributes, children, and text content. ### Properties - **tagName** (string) - Element tag; the default `Doc` uppercases it. - **namespaceURI** (string) - Namespace resolved by the parser. - **outerHTML** (string) - Serialized markup. - **childNodes** (Array) - All children in insertion order. - **children** (Array) - Element-only children in insertion order. - **attributes** (NamedNodeMapLike) - Attribute map. - **textContent** (string) - Concatenated descendant text (settable). ### Methods #### setAttribute(name: string, value?: string): void Set an attribute; default value is `''`. #### appendChild(node: NodeLike | ElementLike | DocumentFragmentLike): void Append a child; fragments are flattened. ``` -------------------------------- ### parse function signature with ParseReturn conditional type Source: https://github.com/beforesemicolon/html-parser The parse function is the library's public API. It accepts an HTML string and an optional handler (a DocumentLike factory or a callback). The generic default D resolves against the standard DOM Document type, and the ParseReturn conditional type maps DocumentLike handlers to DocumentFragmentLike, otherwise to DocumentFragment. ```TypeScript type ParseReturn = T extends DocumentLike ? DocumentFragmentLike : DocumentFragment export const parse = >( markup: string, handler: D | NodeHandlerCallback = Doc as D ): ParseReturn => { ``` -------------------------------- ### NodeHandlerCallback type declaration Source: https://github.com/beforesemicolon/html-parser Declared at src/parse.ts:9, this callback type is used by parse when a function is passed as the handler. It receives each created node as an ElementLike or NodeLike instance. ```TypeScript export type NodeHandlerCallback = (node: ElementLike | NodeLike) => void ```