Unist Node Selector Utility

5.1.0 · active · verified Sun Apr 19

unist-util-select is a utility designed to query and match nodes within a unist (Universal Syntax Tree) abstract syntax tree using CSS-like selectors. The package is currently at stable version 5.1.0 and maintains an active release cadence, with multiple minor and major updates in the past year, reflecting ongoing development and adherence to modern JavaScript standards. Key differentiators include its ability to work with any unist syntax tree and select all node types, providing equivalents to DOM's `querySelector`, `querySelectorAll`, and `matches`. However, it's important to note that unlike the DOM, unist nodes do not inherently store parent references, meaning certain parent-sensitive selectors (e.g., `:first-child`) will not function as they do in a browser environment. For performance-critical scenarios involving numerous modifications, alternatives like `unist-util-visit` might be more efficient, as `unist-util-select` walks the entire tree on each call. For `hast` (HTML AST) specific element selections, `hast-util-select` is recommended.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `matches`, `select`, and `selectAll` to query a unist tree with CSS-like selectors, including handling different selector types and multiple results.

import { u } from 'unist-builder';
import { matches, select, selectAll } from 'unist-util-select';

const tree = u('blockquote', [
  u('paragraph', [u('text', 'Alpha')]),
  u('paragraph', [u('text', 'Bravo')]),
  u('code', 'Charlie'),
  u('paragraph', [u('text', 'Delta')]),
  u('paragraph', [u('text', 'Echo')]),
  u('paragraph', [u('text', 'Foxtrot')]),
  u('paragraph', [u('text', 'Golf')])
]);

console.log('Matches blockquote or list:', matches('blockquote, list', tree));

const selectedNode = select('code ~ :nth-child(even)', tree);
console.log('Selected single node (Delta):', selectedNode ? selectedNode.children[0].value : 'None');

const allSelectedNodes = selectAll('code ~ :nth-child(even)', tree);
console.log('Selected all nodes (Delta, Foxtrot):', allSelectedNodes.map(node => node.children[0].value));

view raw JSON →