HAST Utility to Parse CSS Selectors

4.0.0 · active · verified Sun Apr 19

`hast-util-parse-selector` is a focused utility within the `unified` ecosystem designed to create HAST (Hypertext Abstract Syntax Tree) element nodes from simple CSS selector strings. Currently at stable version 4.0.0, this package follows semantic versioning, with major releases typically aligning with dropping support for unmaintained Node.js versions. It processes basic selectors that can include a tag name, multiple class names, and a single ID, transforming them into a `hast` element object with corresponding `tagName` and `properties` (including `id` and `className` arrays). While powerful for its specific use case, it explicitly states its niche nature, recommending more comprehensive alternatives like `hastscript` or `hast-util-from-selector` for handling complex CSS selectors. Its primary differentiator is its simplicity and directness in parsing straightforward selectors into HAST nodes, making it suitable for scenarios where a full-blown selector engine is overkill.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create `hast` element nodes using various simple CSS selectors and `defaultTagName` options, including class names, IDs, and custom tag fallbacks.

import { parseSelector } from 'hast-util-parse-selector';
import type { Element } from 'hast'; // Import for type definition

// Create a HAST element from a complex class/id selector
const complexSelectorElement: Element = parseSelector('.quux#bar.baz.qux');
console.log('Complex Selector Result:', complexSelectorElement);
// Expected: { type: 'element', tagName: 'div', properties: { id: 'bar', className: [ 'quux', 'baz', 'qux' ] }, children: [] }

// Create a HAST element with a specific tag name and ID
const spanElement: Element = parseSelector('span#foo');
console.log('Span with ID Result:', spanElement);
// Expected: { type: 'element', tagName: 'span', properties: { id: 'foo' }, children: [] }

// Create an element with a default tag name when no selector is provided
const defaultElement: Element = parseSelector(undefined, 'p');
console.log('Default Tag Name Result:', defaultElement);
// Expected: { type: 'element', tagName: 'p', properties: {}, children: [] }

// Using an empty string selector also results in the default tag name
const emptySelectorElement: Element = parseSelector('');
console.log('Empty Selector Result:', emptySelectorElement);
// Expected: { type: 'element', tagName: 'div', properties: {}, children: [] }

// Example with a different default tag name
const customDefaultElement: Element = parseSelector('.my-class', 'section');
console.log('Custom Default Tag Name Result:', customDefaultElement);
// Expected: { type: 'element', tagName: 'section', properties: { className: [ 'my-class' ] }, children: [] }

view raw JSON →