### 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: RecordHello 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 '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('