HAST Utility for Class Names

3.0.0 · active · verified Sun Apr 19

hast-util-classnames is a utility package within the unified collective, designed to simplify the management and merging of CSS class names on HAST (HTML Abstract Syntax Tree) elements. It provides a programmatic API to concatenate, conditionally include, or remove classes, analogous to popular string-based classname utilities but operating directly on HAST nodes. The package is currently at version 3.0.0, which requires Node.js 16 or higher and is distributed exclusively as an ES module (ESM). New major versions typically coincide with dropping support for unmaintained Node.js versions or significant API changes, ensuring compatibility with current Node.js releases. Its key differentiator is its deep integration with the HAST ecosystem, allowing direct manipulation of `properties.className` arrays on HAST element nodes, which is more robust than string manipulation when working with syntax trees.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates both ways to use `classnames`: merging an array of strings and modifying a HAST node's `className` property in place.

import {h} from 'hastscript';
import {classnames} from 'hast-util-classnames';

// Example 1: Merging class names as an array of strings
const mergedClasses = classnames('alpha bravo', {bravo: false, charlie: true}, [123, 'delta']);
console.log('Merged Classes (array):', mergedClasses);
// Expected output: ['alpha', '123', 'charlie', 'delta']

// Example 2: Modifying classes on a HAST node in place
const node = h('p.initial-class', 'Hello, HAST!');
console.log('Original Node:', JSON.stringify(node, null, 2));

const modifiedNode = classnames(node, 'new-class', {conditional: true, 'old-class': false}, ['another-one']);
console.log('Modified Node:', JSON.stringify(modifiedNode, null, 2));
/*
Expected output (simplified):
{
  "type": "element",
  "tagName": "p",
  "properties": {"className": ["initial-class", "new-class", "conditional", "another-one"]},
  "children": [{"type": "text", "value": "Hello, HAST!"}]
}
*/

view raw JSON →