### UltraHTML Query Selector Functions (JavaScript)
Source: https://github.com/natemoo-re/ultrahtml/blob/main/CHANGELOG.md
Introduces the `ultrahtml/selector` module, providing `querySelector`, `querySelectorAll`, and `matches` functions for DOM traversal and selection using CSS selectors. The example shows how to parse HTML, find an element using `querySelector`, and check if an element matches a selector using `matches`. Note that not all CSS selectors may be implemented.
```javascript
import { parse } from "ultrahtml";
import { querySelectorAll, matches } from "ultrahtml/selector";
const doc = parse(`
Demo
/head>
Hello world!
`);
const h1 = querySelector(doc, "h1");
const match = matches(h1, "h1");
```
--------------------------------
### Sanitizing HTML with UltraHTML's `sanitize` Transformer
Source: https://github.com/natemoo-re/ultrahtml/blob/main/CHANGELOG.md
Illustrates the `sanitize` transformer, which can remove or modify HTML elements based on provided options. The `unblockElements` option helps in removing elements without dropping child content. This example shows fixing sanitization of nested elements.
```javascript
const output = await transform("Hello world!
", [
sanitize({ blockElements: ["h1", "strong"] }),
]);
```
--------------------------------
### Async AST Traversal with UltraHTML Walk
Source: https://github.com/natemoo-re/ultrahtml/blob/main/README.md
Demonstrates how to asynchronously traverse an Abstract Syntax Tree (AST) generated by UltraHTML using the `walk` function. This is useful for scanning nodes, performing validations, or modifying the tree, and it must be awaited. It handles potential async components within the tree.
```javascript
import { parse, walk, ELEMENT_NODE } from "ultrahtml";
const ast = parse(`Hello world!
`);
await walk(ast, async (node) => {
if (node.type === ELEMENT_NODE && node.name === "script") {
throw new Error("Found a script!");
}
});
```
--------------------------------
### Query HTML AST with CSS selectors
Source: https://context7.com/natemoo-re/ultrahtml/llms.txt
Demonstrates how to parse HTML into an AST and query it using CSS selectors. Supports complex selectors, pseudo-classes, and element matching.
```javascript
import { parse, render } from "ultrahtml";
import { querySelector, querySelectorAll, matches } from "ultrahtml/selector";
const doc = parse(`
`);
const title = querySelector(doc, "#title");
const items = querySelectorAll(doc, ".item");
const activeItem = querySelector(doc, "li.item.active");
const isActive = matches(activeItem, ".active");
const nestedItems = querySelectorAll(doc, ".container > ul > li");
```
--------------------------------
### Traverse AST with walk/walkSync in ultrahtml
Source: https://context7.com/natemoo-re/ultrahtml/llms.txt
Traverses the Abstract Syntax Tree (AST) depth-first using ultrahtml's `walk` (async) or `walkSync` (sync) functions. A callback is executed for each node, allowing for data collection, validation, or modification. Useful for finding specific nodes or validating tree structure.
```javascript
import { parse, walk, walkSync, ELEMENT_NODE, TEXT_NODE } from "ultrahtml";
const doc = parse(`
Title
Paragraph with link
`);
// Async walk - collect all element names
const elementNames = [];
await walk(doc, async (node) => {
if (node.type === ELEMENT_NODE) {
elementNames.push(node.name);
}
});
console.log(elementNames); // ["div", "h1", "p", "a", "script"]
// Sync walk - find all text content
const textContent = [];
walkSync(doc, (node) => {
if (node.type === TEXT_NODE && node.value.trim()) {
textContent.push(node.value.trim());
}
});
console.log(textContent); // ["Title", "Paragraph with", "link"]
// Validate for dangerous elements
walkSync(doc, (node) => {
if (node.type === ELEMENT_NODE && node.name === "script") {
throw new Error("Found a script element!");
}
});
```
--------------------------------
### Traversing AST with UltraHTML
Source: https://context7.com/natemoo-re/ultrahtml/llms.txt
The `walk` and `walkSync` functions traverse the AST depth-first, executing a callback for each node. `walk` is for asynchronous operations, and `walkSync` is for synchronous traversal.
```APIDOC
## walk / walkSync
### Description
Traverses the AST depth-first, calling a callback for each node. Use `walk` for async operations and `walkSync` for synchronous traversal.
### Method
`walk(node, callback)` or `walkSync(node, callback)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { parse, walk, walkSync, ELEMENT_NODE, TEXT_NODE } from "ultrahtml";
const doc = parse(`
Title
Paragraph with link
`);
// Async walk - collect all element names
const elementNames = [];
await walk(doc, async (node) => {
if (node.type === ELEMENT_NODE) {
elementNames.push(node.name);
}
});
console.log(elementNames); // ["div", "h1", "p", "a", "script"]
// Sync walk - find all text content
const textContent = [];
walkSync(doc, (node) => {
if (node.type === TEXT_NODE && node.value.trim()) {
textContent.push(node.value.trim());
}
});
console.log(textContent); // ["Title", "Paragraph with", "link"]
// Validate for dangerous elements
walkSync(doc, (node) => {
if (node.type === ELEMENT_NODE && node.name === "script") {
throw new Error("Found a script element!");
}
});
```
### Response
#### Success Response (200)
- **void** - The function does not return a value, but executes the callback for each node.
#### Response Example
None (side effects from callback execution)
```
--------------------------------
### Synchronous AST Traversal with UltraHTML WalkSync
Source: https://github.com/natemoo-re/ultrahtml/blob/main/README.md
Illustrates the synchronous traversal of an AST using UltraHTML's `walkSync` function. This method is suitable when it's guaranteed that no asynchronous operations are involved in the AST, offering a simpler, non-awaitable alternative to `walk`.
```javascript
import { parse, walkSync, ELEMENT_NODE } from "ultrahtml";
const ast = parse(`Hello world!
`);
walkSync(ast, (node) => {
if (node.type === ELEMENT_NODE && node.name === "script") {
throw new Error("Found a script!");
}
});
```
--------------------------------
### Ultrahtml h and Fragment: Programmatic AST Node Creation
Source: https://context7.com/natemoo-re/ultrahtml/llms.txt
The `h` and `Fragment` utilities from Ultrahtml allow for programmatic creation of Abstract Syntax Tree (AST) nodes, compatible with JSX transforms. They can be used directly or with JSX transpilers. The `render` function is used to convert AST nodes back to HTML strings.
```javascript
import { h, Fragment, render } from "ultrahtml";
// Create elements programmatically
const element = h("div", { class: "container" },
h("h1", null, "Title"),
h("p", null, "Paragraph text")
);
console.log(await render(element));
// ''
// Use Fragment for multiple root elements
const fragment = h(Fragment, null,
h("li", null, "Item 1"),
h("li", null, "Item 2")
);
// With JSX (requires transpiler configuration)
// tsconfig.json: { "jsxImportSource": "ultrahtml" }
const jsx = (
);
// Component functions work with h()
function Card(props, ...children) {
return h("div", { class: "card", ...props }, ...children);
}
const card = h(Card, { id: "main" }, h("p", null, "Content"));
```
--------------------------------
### Render AST to HTML with ultrahtml
Source: https://context7.com/natemoo-re/ultrahtml/llms.txt
Serializes an Abstract Syntax Tree (AST) node back into an HTML string using ultrahtml. The `render` function supports asynchronous operations, while `renderSync` is for synchronous-only trees. It can render an entire document or specific elements.
```javascript
import { parse, render, renderSync } from "ultrahtml";
// Parse and render back to string
const doc = parse(`Hello world!
`);
const output = await render(doc);
console.log(output); // "Hello world!
"
// Synchronous rendering when no async components exist
const syncOutput = renderSync(doc);
console.log(syncOutput); // "Hello world!
"
// Render a specific element from the tree
const doc2 = parse(`Target
`);
const span = doc2.children[0].children[0];
console.log(await render(span)); // "Target"
```
--------------------------------
### Rendering AST to HTML with UltraHTML
Source: https://context7.com/natemoo-re/ultrahtml/llms.txt
The `render` and `renderSync` functions serialize an AST node back into an HTML string. `render` is asynchronous and supports async components, while `renderSync` is for synchronous operations.
```APIDOC
## render / renderSync
### Description
Serializes an AST node back into an HTML string. The async `render` function supports async components while `renderSync` is for synchronous-only trees.
### Method
`render(node, options?)` or `renderSync(node, options?)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { parse, render, renderSync } from "ultrahtml";
// Parse and render back to string
const doc = parse(`Hello world!
`);
const output = await render(doc);
console.log(output); // "Hello world!
"
// Synchronous rendering when no async components exist
const syncOutput = renderSync(doc);
console.log(syncOutput); // "Hello world!
"
// Render a specific element from the tree
const doc2 = parse(`Target
`);
const span = doc2.children[0].children[0];
console.log(await render(span)); // "Target"
```
### Response
#### Success Response (200)
- **HTML String** (string) - The serialized HTML string.
#### Response Example
```html
Hello world!
```
```
--------------------------------
### Inline CSS Transformation with UltraHTML
Source: https://github.com/natemoo-re/ultrahtml/blob/main/CHANGELOG.md
Shows how to use the `inline` transformer to inline CSS from `
Hello
World
`, [inline()]);
console.log(output);
// 'Hello
// World
'
// Support for media queries with environment
const responsive = await transform(`
Content
`, [inline({ env: { width: 1024, height: 768 } })]);
// Output as object syntax (for frameworks like React)
const objectStyle = await transform(`
Text
`, [inline({ useObjectSyntax: true })]);
```
--------------------------------
### Ultrahtml Scope Transformer: CSS Scoping for Component Isolation
Source: https://context7.com/natemoo-re/ultrahtml/llms.txt
The scope transformer isolates CSS rules by adding data attributes to elements and updating selectors. This prevents style leakage in component-based architectures. It supports auto-generated hashes, custom hashes for consistency, and selective scoping based on attributes.
```javascript
import { transform } from "ultrahtml";
import scope from "ultrahtml/transformers/scope";
// Auto-generated hash for scoping
const scoped = await transform(`
Title
Content
`, [scope()]);
// Elements get data-scope attributes, CSS selectors are updated
// Custom hash for consistent scoping
const customScoped = await transform(`
Text
`, [scope({ hash: "abc123" })]);
// Outputs: '
// Text
'
// Scope only styles with specific attribute
const selective = await transform(`
Scoped
Not scoped
`, [scope({ attribute: "scoped" })]);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.