HAST Element Check Utility

3.0.0 · active · verified Sun Apr 19

This package, `hast-util-is-element`, is a fundamental utility within the HAST (Hypertext Abstract Syntax Tree) ecosystem, primarily designed to check if a given HAST node represents an HTML element. It offers flexible testing capabilities, allowing developers to verify not only if a node is an element but also if it matches specific tag names, an array of tag names, or even complex criteria through a predicate function. The library is currently stable at version 3.0.0, which introduced significant changes, including a migration to ESM-only distribution and a requirement for Node.js 16 or newer. Its release cadence is generally tied to updates within the broader syntax-tree ecosystem, including HAST type definition improvements and Node.js version alignment. A key differentiator is its specialized focus on HAST nodes, providing a more targeted and potentially performant alternative compared to the more generic `unist-util-is` for general Unist nodes. For advanced matching based on CSS selectors, `hast-util-select` offers more robust capabilities, positioning `hast-util-is-element` as a lightweight yet powerful tool for basic and custom element checks.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `isElement` function to check different HAST nodes against various criteria, including tag names, arrays of tag names, and custom predicate functions.

import { isElement } from 'hast-util-is-element';
import { type Element, type Text } from 'hast'; // Assuming 'hast' types are installed

// Example HAST nodes
const textNode: Text = { type: 'text', value: 'foo' };
const anchorNode: Element = { type: 'element', tagName: 'a', properties: { href: '#' }, children: [] };
const divNode: Element = { type: 'element', tagName: 'div', properties: { id: 'main', class: ['container', 'flex'] }, children: [] };
const imgNode: Element = { type: 'element', tagName: 'img', properties: { src: 'image.png' }, children: [] };

console.log('Is textNode an element?', isElement(textNode)); // => false
console.log('Is anchorNode an element?', isElement(anchorNode)); // => true
console.log('Is anchorNode an "a" element?', isElement(anchorNode, 'a')); // => true
console.log('Is imgNode an "img" element?', isElement(imgNode, 'img')); // => true
console.log('Is anchorNode a "b" element?', isElement(anchorNode, 'b')); // => false
console.log('Is divNode an "a" or "div" element?', isElement(divNode, ['a', 'div'])); // => true

// More complex test using a predicate function
console.log('Is divNode a div with class "container"?', 
  isElement(divNode, (node) => node.tagName === 'div' && (node.properties?.class as string[])?.includes('container'))); // => true

view raw JSON →