### Initialize DOMParser
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates how to import and initialize the DOMParser. It shows the basic setup for creating a parser instance and preparing the HTML source string for parsing. Includes an example of dynamically importing the parser on the server side.
```ts
import { Parser } from '@thednp/domparser';
// initialize
const parser = Parser();
// source
const html = source.trim();
/*
// or dynamically import it on your server side
const html = (await fs.readFile("/path-to/index.html", "utf-8")).trim();
*/
```
--------------------------------
### Initialize and Parse with DomParser (TypeScript)
Source: https://github.com/thednp/domparser/blob/master/README.md
This snippet demonstrates how to import and initialize the DomParser. It then shows how to parse an empty string to get a basic document-like root node, which can be used to build a DOM tree from scratch.
```typescript
import { DomParser } from '@thednp/domparser';
// initialize
const doc = DomParser().parseFromString().root;
```
--------------------------------
### Full DOM Tree Representation Example (TypeScript)
Source: https://github.com/thednp/domparser/blob/master/README.md
This example provides a comprehensive representation of a parsed HTML markup as a DOM tree. It details the structure including document, html, head, body, and various child nodes like elements, text, and comments.
```typescript
/*
{
"nodeName": "#document",
"children": [
{
"tagName": "html",
"nodeName": "HTML",
"attributes": {},
"children": [
{
"tagName": "head",
"nodeName": "HEAD",
"attributes": {},
"children": [
{
"tagName": "meta",
"nodeName": "META",
"attributes": {
"charset": "UTF-8"
},
"children": []
},
{
"tagName": "title",
"nodeName": "TITLE",
"attributes": {},
"children": [
{
"nodeName": "#text",
"nodeValue": "Example"
}
]
}
]
},
{
"tagName": "body",
"nodeName": "BODY",
"attributes": {},
"children": [
{
"tagName": "h1",
"nodeName": "H1",
"attributes": {},
"children": [],
"children": [
{
"nodeName": "#text",
"nodeValue": "Hello World!"
}
]
},
{
"tagName": "p",
"nodeName": "P",
"attributes": {
"class": "example",
"aria-hidden": "true"
},
"children": [
{
"nodeName": "#text",
"nodeValue": "This is an example."
}
]
},
{
"tagName": "custom-element",
"nodeName": "CUSTOM-ELEMENT",
"attributes": {},
"children": []
},
{
"nodeName": "#comment",
"nodeValue": ""
},
{
"nodeName": "#comment",
"nodeValue": ""
},
{
"nodeName": "#text",
"nodeValue": "Some text node."
},
{
"tagName": "Counter",
"nodeName": "COUNTER",
"attributes": {
"count": "0"
},
"children": []
}
]
}
]
}
]
}
*/
```
--------------------------------
### DomParser Error Handling Examples
Source: https://github.com/thednp/domparser/blob/master/README.md
Shows examples of how DomParser throws specific errors when provided with invalid parameters, such as non-object input for the main constructor or non-string input for parsing.
```typescript
DomParser("invalid");
// > DomParserError: 1st parameter is not an object
DomParser.parserFromString({});
// > DomParserError: 1st parameter is not a string
```
--------------------------------
### HTML Source Markup Example
Source: https://github.com/thednp/domparser/blob/master/README.md
A sample HTML structure used to demonstrate the capabilities of the DOMParser, including special tags, comments, and text nodes. It showcases how the parser handles various HTML elements and special content.
```html
Example
Hello World!
This is an example.
Some text node.
```
--------------------------------
### Creating DOM Elements with DomParser (TypeScript)
Source: https://github.com/thednp/domparser/blob/master/README.md
This example illustrates how to use Document-like methods provided by the DomParser's root node to create new DOM elements. It shows how to specify the tag name, attributes, and child nodes for the new element.
```typescript
const html = doc.createElement(
"html", // tagName
{ class: "html-class" }, // attributes
doc.createElement("head") // childNodes
// ...other child nodes
);
```
--------------------------------
### Create Document Root Node
Source: https://github.com/thednp/domparser/blob/master/README.md
Provides documentation for the `createDocument` function, which is used to create a new `Document` like root node for DOM manipulation. It includes a TypeScript type definition and a quick usage example.
```typescript
/**
* Creates a new `Document` like root node.
*
* @returns a new root node
*/
const createDocument = () => RootNode;
import { createDocument } from "@thednp/domparser/dom";
// create a root node
const doc = createDocument();
// use the available methods
const html = doc.createElement("html");
```
--------------------------------
### Log DOMParser Components
Source: https://github.com/thednp/domparser/blob/master/README.md
Illustrates how to access and log the identified components from the parsed HTML. Components are typically custom elements or framework-specific tags detected by the parser. The output shows examples of custom elements and UI framework components.
```js
// list all components
console.log(components);
/*
[
// this looks like a CustomElement,
// you can get it via customElements.get('custom-element')
"custom-element",
// this looks like a UI framework component
// handle it accordingly
"Counter"
]
*/
```
--------------------------------
### Create Root Node using DomParser
Source: https://github.com/thednp/domparser/blob/master/README.md
Creates a root node for a document using the DomParser.parseFromString method. This method can be invoked with or without starting HTML markup.
```typescript
import { DomParser } from "@thednp/domparser/dom-parser";
// create a root node
const doc = DomParser.parseFromString().root;
```
--------------------------------
### Append Nodes using Node API - TypeScript
Source: https://github.com/thednp/domparser/blob/master/README.md
Illustrates the Node API's methods for appending nodes: append (multiple nodes), appendChild (single node), before (nodes before target), and after (nodes after target). This example shows creating elements and structuring them within a document.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// Create a root document.
const doc = createDocument();
// Create elements and append new nodes
const html = doc.createElement("html");
const body = doc.createElement("body");
const head = doc.createElement("head");
// Append a single node
html.append(head);
// Append one or more nodes after the target node
head.after(body);
// Append the new element to the root node
doc.appendChild(html);
```
--------------------------------
### Element - Set, Check, and Get Namespace Attributes
Source: https://github.com/thednp/domparser/blob/master/README.md
Details the process of handling namespace attributes, particularly for elements like SVG. Uses 'setAttributeNS' with a namespace URI, 'hasAttributeNS' to verify attribute presence within a namespace, and 'getAttributeNS' to retrieve the attribute's value.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// create a root document
const doc = createDocument();
// namespaced attributes
const svg = doc.createElementNS("http://www.w3.org/2000/svg", "svg",
// alternativelly add an attributes object here
)
// set attributes
svg.setAttributeNS("http://www.w3.org/2000/svg", "xmlns", "http://www.w3.org/2000/svg");
svg.setAttributeNS("http://www.w3.org/2000/svg", "viewBox", "0 0 24 24");
// check attribute
svg.hasAttributeNS("http://www.w3.org/2000/svg", "viewBox");
// => true
// get attribute
svg.getAttributeNS("http://www.w3.org/2000/svg", "xmlns");
// => "http://www.w3.org/2000/svg"
```
--------------------------------
### Element - Set, Check, and Get Non-Namespace Attributes
Source: https://github.com/thednp/domparser/blob/master/README.md
Explains how to manage non-namespace attributes for an Element. Uses 'setAttribute' to define an attribute, 'hasAttribute' to check for its existence, and 'getAttribute' to retrieve its value. Direct property access like 'html.id' is also supported for common attributes.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// create a root document
const doc = createDocument();
// create a non-namespace node
const html = doc.createElement("html",
// alternatively you could add an attributes object here
);
// set attribute
html.setAttribute("id", "app-head");
// check attribute
html.hasAttribute("id");
// => true
// get attribute
html.getAttribute("id");
// common attribute
html.id;
html.className;
```
--------------------------------
### Handle Mismatched Closing Tags with DomParser Error
Source: https://github.com/thednp/domparser/blob/master/README.md
Illustrates error handling in the DomParser when encountering critical parsing issues, such as mismatched closing tags. The example shows how DomParser throws a specific 'DomParserError' for such critical errors, while generally attempting to parse malformed HTML gracefully.
```typescript
DomParser().parseFromString("
");
//=> "DomParserError: Mismatched closing tag: . Expected closing tag for ."
```
--------------------------------
### Access Element Content with Node & Element API
Source: https://github.com/thednp/domparser/blob/master/README.md
Explains how to access and modify the content of DOM elements using `innerHTML`, `outerHTML`, and `textContent` properties. `innerHTML` gets/sets the HTML markup within an element, `outerHTML` gets the element's complete markup, and `textContent` gets/sets the plain text content.
```typescript
import { createDocument } from "@thednp/domparser/dom";
const doc = createDocument();
doc.append(doc.createElement("body"));
// Create some elements
const div = doc.createElement("div", { id: "myDiv" });
const p1 = doc.createElement("p", "Paragraph 1");
const p2 = doc.createElement("p", "Paragraph 2");
div.append(p1, p2);
doc.body.append(div);
// innerHTML
console.log(div.innerHTML);
// =>
`
Paragraph 1
Paragraph 2
`
// outerHTML
console.log(div.outerHTML);
// =>
`
`
// get() textContent
console.log(div.textContent);
// =>
`
Paragraph 1
Paragraph 2
`
// set() textContent
div.textContent = "A new Node";
console.log(div.textContent);
// =>
`
A new Node
`
```
--------------------------------
### Create Element and SVGElement Nodes
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates creating Element and SVGElement nodes using the document's createElement and createElementNS methods. It shows how to define attributes and child nodes during creation.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// create a root document
const doc = createDocument();
// create `Element` like nodes
const html = doc.createElement("html",
// define an attributes object as second parameter
// and/or define multiple child nodes as additional parameters
);
// =>
// create `SVGElement` like nodes or namespace
const svg = doc.createElementNS(
"http://www.w3.org/2000/svg", // namespace
"svg", // tagName
{ // attributes
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
},
// define multiple child nodes as additional parameters
);
// =>
```
--------------------------------
### Import Specific Components from DOMParser for Tree-Shaking
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates how to import individual components like Parser, DomParser, or createDocument from the @thednp/domparser library. This allows for efficient tree-shaking, ensuring only the necessary code is bundled, thus reducing application size.
```typescript
// import Parser only
import { Parser } from "@thednp/domparser/parser"
// import DomParser only
import { DomParser } from "@thednp/domparser/dom-parser"
// import createDocument only
import { createDocument } from "@thednp/domparser/dom"
```
--------------------------------
### Create Text and Comment Nodes
Source: https://github.com/thednp/domparser/blob/master/README.md
Illustrates the creation of text and comment nodes using createTextNode and createComment methods. It also shows how these nodes can be appended to elements and how they can be automatically created when providing strings to createElement.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// Create a root document
const doc = createDocument();
// Create a text node
const textNode = doc.createTextNode("This is some text.");
// Create a comment node
const commentNode = doc.createComment("This is a comment.");
// Create an element to hold the nodes
const paragraph = doc.createElement("p");
// Append the text and comment nodes to the element
paragraph.append(textNode, commentNode);
// Append the element to the document body
doc.body.append(paragraph);
// Access the child nodes, including the text and comment
console.log(paragraph.childNodes);
// Output:
/*
[
{ nodeName: '#text', nodeValue: 'This is some text.' },
{ nodeName: '#comment', nodeValue: '' }
]
*/
```
```typescript
import { createDocument } from "@thednp/domparser/dom";
// Create a root document.
const doc = createDocument();
// Create a new paragraph element with text and comment nodes.
const paragraph = doc.createElement("p",
"This is text content.", // Automatically creates a text node.
"", // Automatically creates a comment node
);
console.log(paragraph.childNodes);
// Output:
/*
[
{ nodeName: '#text', nodeValue: 'This is text content.' },
{ nodeName: '#comment', nodeValue: '' }
]
*/
```
--------------------------------
### Create DOM Tree with Single Call (TypeScript)
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates creating an entire DOM tree, including nested elements and attributes, using a single `createDocument` call. This method simplifies DOM construction compared to native APIs.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// create a root document
const doc = createDocument();
// create the entire page if you like
doc.createElement("html", // tagName
{ class: "html-class" }, // attributes
doc.createElement("head", // childNodes
// the following syntax call will automatically create a `#text` node
doc.createElement("title", "This is a title"),
doc.createElement("meta", {
name: "description",
content: "Some description",
}),
),
doc.createElement("body",
// attributes can be optional
doc.createElement("h1", "This is a heading"),
doc.createElement("p", "This is a paragraph"),
),
);
```
--------------------------------
### Query DOM with Element API
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates using the Element API for DOM querying, including methods like getElementsByTagName, querySelectorAll, querySelector, closest, getElementsByClassName, and children.find. Note that CSS pseudo-selectors are not supported.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// create a root document
const doc = createDocument();
// create a DOM tree
doc.append(
doc.createElement("html",
doc.createElement("head",
doc.createElement("title", "Page title")
),
doc.createElement("body",
doc.createElement("main", { class: "container" },
doc.createElement("h1", "Page title"),
doc.createElement("p", { class: "lead" }, "Lead paragraph"),
doc.createElement("p", "Second paragraph"),
doc.createElement("button", { "data-toggle": "popover" }, "Read more"),
)
)
)
);
const paragraphs = doc.body.getElementsByTagName("p");
// => [p, p]
const contentItems = doc.body.querySelectorAll("h1, p");
// => [h1, p, p]
const heading = doc.body.querySelector("h1");
// => h1
const main = heading.closest("main");
// => main
const allContents = main.getElementsByTagName("*");
// => [h1, p.lead, p, button[data-toggle]]
doc.head.contains(heading);
// => false
doc.contains(heading);
// => true
const lead = doc.documentElement.getElementsByClassName("lead");
// => [p.lead]
const button = main.children.find(child => child.matches("[data-toggle]"))
// => button[data-toggle="popover"]
```
--------------------------------
### Basic HTML Parsing with Parser Function
Source: https://context7.com/thednp/domparser/llms.txt
Demonstrates how to use the lightweight Parser function to create a simple DOM tree from HTML markup. It returns the root document, a list of detected tags, and component names. This is useful for basic HTML tokenization.
```typescript
import { Parser } from '@thednp/domparser';
const parser = Parser();
const html = `
Example
Hello World!
This is an example.
`;
const { root, tags, components } = parser.parseFromString(html);
console.log(tags);
// Output: ['html', 'head', 'meta', 'title', 'body', 'h1', 'p']
console.log(components);
// Output: ['custom-element', 'Counter']
console.log(root.children[0].tagName);
// Output: 'html'
console.log(root.children[0].children[1].children[0].attributes);
// Output: { class: 'example' }
```
--------------------------------
### Content Properties: innerHTML, outerHTML, textContent (TypeScript)
Source: https://context7.com/thednp/domparser/llms.txt
Illustrates how to access and modify the content of DOM elements using innerHTML, outerHTML, and textContent properties. innerHTML retrieves the HTML of child elements, outerHTML includes the element itself, and textContent gets only the text content.
```typescript
import { DomParser } from '@thednp/domparser';
const { root: doc } = DomParser().parseFromString(`
Title
First paragraph
Second paragraph
`);
const content = doc.getElementById('content');
// Get innerHTML (child elements as HTML string)
console.log(content.innerHTML);
// Output:
// Title
// First paragraph
// Second paragraph
// Get outerHTML (including the element itself)
console.log(content.outerHTML);
// Output:
//
//
Title
// ...
//
// Get textContent (text only, no tags)
console.log(content.textContent);
// Output:
// Title
// First paragraph
// Second paragraph
// Set textContent (replaces all children with text node)
const heading = doc.querySelector('h1');
heading.textContent = 'New Title';
console.log(heading.textContent);
// Output: 'New Title'
console.log(heading.childNodes.length);
// Output: 1
console.log(heading.childNodes[0].nodeName);
// Output: '#text'
```
--------------------------------
### Programmatic DOM Tree Creation with createDocument
Source: https://context7.com/thednp/domparser/llms.txt
Shows how to use the createDocument function to generate a new Document-like root node for building DOM trees programmatically without parsing existing HTML. This is ideal for creating DOM structures from scratch.
```typescript
import { createDocument } from '@thednp/domparser/dom';
const doc = createDocument();
// Create complete DOM tree in a single call
doc.append(
doc.createElement('html',
doc.createElement('head',
doc.createElement('title', 'My Application'),
doc.createElement('meta', { charset: 'UTF-8' })
),
doc.createElement('body', { class: 'app-body' },
doc.createElement('header',
doc.createElement('h1', 'Welcome')
),
doc.createElement('main', { id: 'content' },
doc.createElement('p', 'First paragraph'),
doc.createElement('p', { class: 'highlight' }, 'Second paragraph')
),
doc.createElement('footer', '© 2024')
)
)
);
console.log(doc.documentElement.outerHTML);
// Output: ......
console.log(doc.body.className);
// Output: 'app-body'
console.log(doc.head.children.length);
// Output: 2
```
--------------------------------
### Create Root Node using createDocument
Source: https://github.com/thednp/domparser/blob/master/README.md
Creates a root node for a document using the createDocument function. This is an alternative method to DomParser.parseFromString for initializing a document.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// create a root node
const doc = createDocument();
```
--------------------------------
### Query DOM Elements with DomParser Selector Engine
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates how to use DomParser's selector engine to find elements by ID, tag name, class name, and through query selectors. It also shows parent-child relationship checks and the closest method. Note that direct-child and pseudo-selectors are not supported.
```typescript
import { DomParser } from "@thednp/domparser/dom-parser";
const { root: doc } = DomParser().parseFromString();
// exclusive to the root node
console.log(doc.getElementById('my-id'));
// returns node with id="my-id" or null otherwise
console.log(doc.getElementsByTagName('*'));
// returns nodes with all tag names
console.log(doc.getElementsByTagName('head'));
// returns an array with only node in this case
console.log(doc.getElementsByClassName('html-head'));
// returns an array with only node in this case
console.log(doc.body.querySelectorAll('h1, p'));
// handles multiple selectors and returns all Heading1 and Paragraphs
// found in the children of the body
// parent-child relationship
console.log(doc.body.contains(svg));
// returns true
console.log(doc.head.contains(svg));
// returns false
console.log(svg.closest("#my-body"));
// returns the `body` object
```
--------------------------------
### Create DOM from HTML with Sanitization using DomParser
Source: https://github.com/thednp/domparser/blob/master/README.md
Illustrates how to use DomParser to create a DOM structure from an HTML string. It includes options for sanitizing the HTML by filtering dangerous tags and attributes to prevent XSS vulnerabilities. The `onNodeCallback` can be used for custom node processing.
```typescript
import { DomParser } from "@thednp/domparser/dom-parser";
const parserOptions = {
// sets a callback to call on every new node
onNodeCallback: (node, parent, root) => {
// apply any validation, sanitization to your node
// and return the SAME node reference
doSomeFunctionWith(node, parent, root);
return node;
},
// Common dangerous tags that could lead to XSS attacks
filterTags: [
"script", "style", "iframe", "object", "embed", "base", "form",
"input", "button", "textarea", "select", "option"
],
// Unsafe attributes that could lead to XSS attacks
filterAttrs: [
"onerror", "onload", "onunload", "onclick", "ondblclick", "onmousedown",
"onmouseup", "onmouseover", "onmousemove", "onmouseout", "onkeydown",
"onkeypress", "onkeyup", "onchange", "onsubmit", "onreset", "onselect",
"onblur", "onfocus", "formaction", "href", "xlink:href", "action"
]
}
const { root: doc } = DomParser(parserOptions).parseFromString(
"This is a basic body",
);
// > the doctype will be added to `doc` as a property;
// > all configured tags and attributes will be removed
// from the resulted parseResult.root object tree.
```
--------------------------------
### Query DOM Elements using CSS Selectors
Source: https://context7.com/thednp/domparser/llms.txt
Explains how to use querySelector and querySelectorAll to find elements based on CSS selectors. The engine caches selectors for performance.
```typescript
import { DomParser } from '@thednp/domparser';
const { root: doc } = DomParser().parseFromString(`
Main Title
Lead paragraph
Visible paragraph
Submit
`);
// Query by ID
const app = doc.getElementById('app');
console.log(app.className);
// Output: 'container'
// Query by CSS selector
const title = doc.querySelector('h1.title');
console.log(title.textContent);
// Output: 'Main Title'
// Query multiple elements
const paragraphs = doc.querySelectorAll('p');
console.log(paragraphs.length);
// Output: 2
// Attribute selector
const visibleElements = doc.querySelectorAll('[data-visible]');
console.log(visibleElements.length);
// Output: 1
// Multiple selectors
const headingsAndParagraphs = doc.querySelectorAll('h1, p');
console.log(headingsAndParagraphs.length);
// Output: 3
// Query from specific element
const bodyParagraphs = doc.body.getElementsByTagName('p');
console.log(bodyParagraphs.length);
// Output: 2
// Get by class name
const leadElements = doc.getElementsByClassName('lead');
console.log(leadElements[0].textContent);
// Output: 'Lead paragraph'
```
--------------------------------
### Create HTML Elements with Attributes and Children
Source: https://context7.com/thednp/domparser/llms.txt
Demonstrates the createElement method for creating HTML elements. It supports adding attributes via an object and children as strings or other elements. Strings are automatically converted to text nodes.
```typescript
import { createDocument } from '@thednp/domparser/dom';
const doc = createDocument();
// Create element with attributes object
const div = doc.createElement('div',
{ id: 'container', class: 'wrapper', 'data-theme': 'dark' }
);
// Create element with text content
const heading = doc.createElement('h1', 'Page Title');
// Create element with attributes and children
const nav = doc.createElement('nav', { class: 'main-nav' },
doc.createElement('a', { href: '#home' }, 'Home'),
doc.createElement('a', { href: '#about' }, 'About'),
doc.createElement('a', { href: '#contact' }, 'Contact')
);
// Append to document
doc.append(doc.createElement('body', div, heading, nav));
console.log(div.id);
// Output: 'container'
console.log(div.className);
// Output: 'wrapper'
console.log(heading.textContent);
// Output: 'Page Title'
console.log(nav.children.length);
// Output: 3
console.log(nav.outerHTML);
// Output: 'Home ... '
```
--------------------------------
### Node - Access Children and ChildNodes
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates how to access children and childNodes of a DOM node. The 'children' property returns only element nodes, while 'childNodes' returns all node types, including comments and text nodes. Nodes must be appended to a parent to be accessible.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// create a root document
const doc = createDocument();
// create nodes
const html = doc.createElement('html');
const head = doc.createElement('head');
const body = doc.createElement('body');
const comment = doc.createComment('This is a comment');
// append nodes to DOM tree
doc.append(html);
html.append(head, body, comment);
// children
console.log(html.children);
// => [head, body]
// childNodes should also list other type of nodes
// such as #text or #comment nodes
console.log(html.childNodes);
// => [head, body, comment]
```
--------------------------------
### Access Child Nodes and Elements (TypeScript)
Source: https://github.com/thednp/domparser/blob/master/README.md
Shows how to access child nodes and elements of a DOM node using `children`, `childNodes`, `all`, `documentElement`, `head`, and `body` accessors. These properties provide different ways to traverse the DOM tree.
```typescript
const doc = createDocument();
// create a target node
const childNode = document.createElement("html");
// now we append the node
doc.append(childNode);
// children accessor
console.log(doc.children);
// => [html]
// childNodes accessor
console.log(doc.childNodes);
// => [html]
// all accessor
console.log(doc.all);
// => [html]
// documentElement accessor
console.log(doc.documentElement);
// => html
// similarly we would have document.head and document.body
// if these nodes have been created and appended
```
--------------------------------
### Parse HTML Source with DOMParser
Source: https://github.com/thednp/domparser/blob/master/README.md
Shows the core parsing operation using the `parseFromString` method of the DOMParser. This method takes the HTML string as input and returns an object containing components, tags, and the root DOM structure.
```ts
// parse the source
const { components, tags, root } = parser.parseFromString(html);
```
--------------------------------
### DOM Parsing with DomParser and Parser in JavaScript
Source: https://github.com/thednp/domparser/blob/master/demo/index.html
This snippet demonstrates how to use the DomParser and Parser classes for parsing HTML strings. It includes a debounce function for efficient event handling and logic to select the parser type based on radio button input. The output shows the parsed DOM, extracted tags, and components.
```javascript
// import { Parser, DomParser, escape } from "../dist/index.mjs";
import { Parser, DomParser, escape } from "../src/index.ts";
// console.log(Parser);
const parsers = {
Parser,
DomParser
}
function debounce(func, delay = 350) {
let timeoutId;
// Variable to store the timeout ID
return function (...args) {
// Return a new function that will be debounced
clearTimeout(timeoutId);
// Clear any existing timeout
timeoutId = setTimeout(() => {
// Set a new timeout
func.apply(this, args);
// Call the original function after the delay
}, delay);
};
}
const radio = Array.from(document.getElementsByTagName("input"));
const [input] = document.getElementsByTagName("textarea");
const [output] = document.getElementsByTagName("output");
const [pre] = document.getElementsByTagName("pre");
const onChange = debounce(() => {
console.time("parsing");
const parserType = radio.find(r => r.checked).value || "DomParser";
const { root: doc, components, tags } = parsers[parserType]({
filterTags: [
// "script",
// "head",
]
}).parseFromString(input.value);
console.timeEnd("parsing");
console.log(doc)
output.innerHTML = `
Parser : ${parserType}
Tags : ${tags.join(', ')}
Components : ${components.length ? components.join(', ') : "none"}
DOM Tree (Click to expand)
${ JSON.stringify(doc, (key, value) => {
if (key === "nodeValue") {
return escape(value)
}
return value;
}, 2) // ""
}
`.trim();
// console.log(htmlParsed)
});
input.addEventListener('input', onChange);
radio.forEach(r => r.addEventListener('input', onChange));
onChange();
```
--------------------------------
### Node Ancestor Relationships - TypeScript
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates how to navigate and check ancestor relationships within the DOM using Node API properties like parentNode and ownerDocument, and the contains method. This is useful for verifying node hierarchy and existence within the document.
```typescript
const doc = createDocument();
const html = doc.createElement("html");
const head = doc.createElement("head");
const title = doc.createElement("title", "My App Title");
// append the html node to the root
doc.append(html);
// append the head node to the html node
html.append(head);
// after the above you can also call
// doc.documentElement.append(head)
// append the title node to the head node
head.append(title);
// check parentNode / parentElement
console.log(title.parentNode);
// OR
console.log(title.parentElement);
// => head
// check ownerDocument
console.log(title.ownerDocument);
// => doc
// check if title is appended
console.log(head.contains(title));
// => true
// check if title and head nodes are appended
console.log(html.contains(title));
// check if title, head and html nodes are appended
console.log(doc.contains(title));
// => true
```
--------------------------------
### Check Node Presence in DOM Tree (TypeScript)
Source: https://github.com/thednp/domparser/blob/master/README.md
Illustrates how to use the `append` and `contains` methods to add nodes to the DOM tree and subsequently check if a specific node exists within it. `append` is the recommended way to add nodes for proper functionality.
```typescript
const doc = createDocument();
// create a target node
const childNode = document.createElement("div");
// check if root node contains a specific node
doc.contains(childNode);
// in this case returns `false` because it hasn't been appended
// to any existing node in the DOM tree
// if we append the node
doc.append(childNode);
doc.contains(childNode);
// this now returns `true`
```
--------------------------------
### Create SVG Elements with Namespaced Attributes
Source: https://context7.com/thednp/domparser/llms.txt
Illustrates the createElementNS method for creating SVG elements within a specified namespace. It allows for the creation of complex SVG structures with attributes.
```typescript
import { createDocument } from '@thednp/domparser/dom';
const doc = createDocument();
const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg',
{ xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 24 24', width: '24', height: '24' },
doc.createElementNS('http://www.w3.org/2000/svg', 'circle',
{ cx: '12', cy: '12', r: '10', fill: 'blue' }
),
doc.createElementNS('http://www.w3.org/2000/svg', 'path',
{ d: 'M12 2v20M2 12h20', stroke: 'white', 'stroke-width': '2' }
)
);
doc.append(doc.createElement('body', svg));
console.log(svg.outerHTML);
// Output: '... '
console.log(svg.getAttribute('viewBox'));
// Output: '0 0 24 24'
```
--------------------------------
### Log DOMParser Tags
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates how to retrieve and log all valid HTML tags found in the parsed document. The `tags` property provides an ordered list of elements as they appear in the source markup, excluding special nodes like comments or doctypes.
```js
// list all tags
console.log(tags);
// ['html', 'head', 'meta', 'title', 'body', 'h1', 'p']
```
--------------------------------
### Remove and Replace Child Nodes (TypeScript)
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates the usage of `removeChild` and `replaceChildren` methods to manage child nodes within the DOM tree. `removeChild` removes a specific child, while `replaceChildren` can remove all children or replace them with new ones.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// create a root document
const doc = createDocument();
// create a child node
const html = doc.createElement('html');
// append a child to the root node
doc.append(html);
// remove a child from the root node
doc.removeChild(html);
// remove all children of the root node
doc.replaceChildren();
// replace children of the root node
doc.replaceChildren(
doc.createElement('html',
doc.createElement('head'),
doc.createElement('body'),
),
);
/* root only methods, internally used */
const html = doc.createElement('html');
```
--------------------------------
### Parse Basic HTML Attributes with getBasicAttributes
Source: https://github.com/thednp/domparser/blob/master/README.md
Parses a string token to extract HTML attributes into an object. It supports an options object for handling unsafe attributes. The function takes the HTML string and an optional configuration object as input, returning a key-value pair of attribute names and their values.
```typescript
/**
* Parse a string token and return an object
* where the keys are the names of the attributes and the values
* are the values of the attributes.
*
* @param tagStr the tring token
* @param config an optional set of options for unsafe attributes
* @returns the attributes object
*/
const getBasicAttributes: (tagStr: string, options) => Record;
import { getBasicAttributes } from "@thednp/domparser";
// define options
const options = {
unsafeAttrs: new Set(["data-url"]),
}
// use the tokenizer methods
const attributes = getBasicAttributes(
// the target string
`html id="html" class="html" data-url="https://example.com/api"`,
// the options
options,
);
// the results
/*
{
id: "html",
class: "html",
}
*/
```
--------------------------------
### DOM Manipulation: append, appendChild, remove (TypeScript)
Source: https://context7.com/thednp/domparser/llms.txt
Demonstrates how to add, remove, and replace nodes in the DOM tree using methods like append, appendChild, removeChild, remove, and replaceChildren. It also shows how to insert nodes relative to existing ones using after.
```typescript
import { createDocument } from '@thednp/domparser/dom';
const doc = createDocument();
const body = doc.createElement('body');
doc.append(doc.createElement('html', body));
// Append multiple children
body.append(
doc.createElement('header', 'Header'),
doc.createElement('main', 'Content'),
doc.createElement('footer', 'Footer')
);
console.log(body.children.length);
// Output: 3
// appendChild for single node
const sidebar = doc.createElement('aside', 'Sidebar');
body.appendChild(sidebar);
console.log(body.children.length);
// Output: 4
// Insert before/after existing nodes
const nav = doc.createElement('nav', 'Navigation');
body.children[0].after(nav);
console.log(body.children[1].tagName);
// Output: 'nav'
// Remove a child
body.removeChild(sidebar);
console.log(body.children.length);
// Output: 4
// Self-remove
body.children[0].remove();
console.log(body.children.length);
// Output: 3
// Replace all children
body.replaceChildren(
doc.createElement('div', { id: 'new-content' }, 'New content')
);
console.log(body.children.length);
// Output: 1
console.log(body.children[0].id);
// Output: 'new-content'
```
--------------------------------
### Query DOM Elements using Document API - TypeScript
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates various methods of the Document API for querying DOM elements, including getElementById, querySelector, querySelectorAll, getElementsByClassName, and getElementsByTagName. It supports comma-separated selectors and attribute selectors, with caching for performance. Direct and pseudo-selectors are not implemented.
```typescript
const doc = createDocument();
doc.append(doc.createElement("div", {
id: "my-div", class: "target", "data-visible": "true"
}));
// find node by ID attribute
doc.getElementById("my-div");
// => div#my-div.target
// find element by CSS selector
doc.querySelector('.target');
// => div#my-div.target
// find elements by attribute CSS selector
doc.querySelectorAll("[data-visible]");
// => [div#my-div.target]
// find elements by multiple selectors
doc.querySelectorAll("p, ul");
// => []
// find elements by class name
doc.getElementsByClassName('target');
// [div#my-div.target]
// find elements by tag name
doc.getElementsByTagName("div");
// => [div#my-div.target]
// find elements by ANY tag name
doc.getElementsByTagName("*");
// => [div#my-div.target]
```
--------------------------------
### Element - Remove, Replace, and Remove Self
Source: https://github.com/thednp/domparser/blob/master/README.md
Illustrates methods for managing child nodes of an Element. 'removeChild' removes a specific child, 'replaceChildren' clears all children or replaces them with new nodes, and 'remove' allows a node to remove itself from the DOM.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// create a root document
const doc = createDocument();
// create nodes
const html = doc.createElement('html');
const body = doc.createElement('body');
// append a child to a parent node
html.append(body);
// remove a child from the parent node
html.removeChild(body);
// remove all children of a given node
html.replaceChildren();
// replace children of a given node
html.replaceChildren(
doc.createElement('body',
doc.createElement('header'),
doc.createElement('main'),
doc.createElement('footer'),
),
);
// any node in the DOM tree
// can just remove itself
html.remove();
```
--------------------------------
### Append Child Nodes to Element
Source: https://github.com/thednp/domparser/blob/master/README.md
Demonstrates appending child nodes to a root node using the append and appendChild methods. The append method allows for multiple nodes to be added at once.
```typescript
import { createDocument } from "@thednp/domparser/dom";
// Create a root document.
const doc = createDocument();
// Create a element and append new nodes to it
const html = doc.createElement("html");
html.append(
doc.createElement("head"),
doc.createElement("body")
);
// Append the new element to the root node
doc.appendChild(html);
```
--------------------------------
### Full DOM API Manipulation with DomParser
Source: https://context7.com/thednp/domparser/llms.txt
Illustrates the use of DomParser for comprehensive DOM-like API capabilities, including element manipulation, selector queries, and HTML sanitization. It handles tag validation and provides configuration options for filtering tags and attributes.
```typescript
import { DomParser } from '@thednp/domparser';
const parserConfig = {
filterTags: ['script', 'iframe', 'object', 'embed'],
filterAttrs: ['onerror', 'onclick', 'onload', 'href'],
onNodeCallback: (node, parent, root) => {
// Custom processing for each node
return node;
}
};
const { root: doc, tags, components } = DomParser(parserConfig)
.parseFromString(`
My App
Welcome
Lead paragraph
Regular paragraph
`);
console.log(doc.doctype);
// Output: ''
console.log(doc.documentElement.tagName);
// Output: 'html'
console.log(doc.head.children[0].textContent);
// Output: 'My App'
console.log(doc.body.innerHTML);
// Output: '...'
// Script tags are filtered out
console.log(doc.getElementsByTagName('script').length);
// Output: 0
```
--------------------------------
### DOM Traversal: parentNode, contains, closest (TypeScript)
Source: https://context7.com/thednp/domparser/llms.txt
Explains how to navigate the DOM tree using parentNode, parentElement, and ownerDocument properties. It also covers checking for node containment with the contains method and finding the closest ancestor element matching a selector using the closest method.
```typescript
import { DomParser } from '@thednp/domparser';
const { root: doc } = DomParser().parseFromString(`
Article Title
Article content
`);
const paragraph = doc.querySelector('p.text');
// Access parent node
console.log(paragraph.parentNode.tagName);
// Output: 'article'
console.log(paragraph.parentElement.className);
// Output: 'post'
// Access owner document
console.log(paragraph.ownerDocument.nodeName);
// Output: '#document'
// Find closest ancestor matching selector
const container = paragraph.closest('.container');
console.log(container.tagName);
// Output: 'div'
const section = paragraph.closest('#content');
console.log(section.tagName);
// Output: 'section'
// Check containment
const article = doc.querySelector('article');
console.log(article.contains(paragraph));
// Output: true
console.log(doc.body.contains(paragraph));
// Output: true
console.log(doc.head?.contains(paragraph));
// Output: undefined (head doesn't exist)
```
--------------------------------
### Accessing the Root of the DOM Tree (TypeScript)
Source: https://github.com/thednp/domparser/blob/master/README.md
This snippet shows how to access the root node of the parsed DOM tree and log it to the console. The root node represents the entire document structure.
```typescript
console.log(root);
/*
{
"nodeName": "#document",
"children": []
}
*/
```
--------------------------------
### CSS Selector Matching - TypeScript
Source: https://context7.com/thednp/domparser/llms.txt
Checks if a DOM element matches a given CSS selector. Implements caching for selectors to improve performance on repeated matches. Demonstrates matching by tag name, ID, class, attributes, and combined selectors.
```typescript
import { DomParser, matchesSelector, selectorCache } from '@thednp/domparser';
const { root: doc } = DomParser().parseFromString(`
Click
`);
const div = doc.querySelector('div');
const button = doc.querySelector('button');
// Match by tag name
console.log(matchesSelector(div, 'div'));
// Output: true
// Match by ID
console.log(matchesSelector(div, '#app'));
// Output: true
// Match by class
console.log(matchesSelector(div, '.container'));
// Output: true
// Match by multiple classes
console.log(matchesSelector(button, '.btn.btn-primary'));
// Output: true
// Match by attribute
console.log(matchesSelector(div, '[data-active]'));
// Output: true
console.log(matchesSelector(div, '[data-active="true"]'));
// Output: true
// Match by attribute value
console.log(matchesSelector(button, '[type="submit"]'));
// Output: true
// Combined selectors
console.log(matchesSelector(div, 'div#app.container'));
// Output: true
// Use element.matches() method
console.log(div.matches('#app'));
// Output: true
// Check selector cache stats
console.log(selectorCache.getStats());
// Output: { size: 8, hits: 0, misses: 8, hitRate: 0 }
```