Parseley: CSS Selectors Parser

0.13.1 · active · verified Tue Apr 21

Parseley is a JavaScript/TypeScript library designed for parsing CSS selector strings into a structured Abstract Syntax Tree (AST) and for serializing those ASTs back into strings. It also automatically calculates CSS specificity for each selector component. As of version 0.13.1, the library provides core functionalities such as `parse1` for parsing individual selectors, `serialize` for converting an AST back into a CSS string, and `normalize` for standardizing the order of simple selectors within an AST. It ships with comprehensive TypeScript types and is compatible with both Node.js and Deno environments. Parseley's AST structure is optimized for right-to-left processing, representing complex selectors via 'combinator' nodes integrated into 'compound' selectors rather than distinct 'complex selector' nodes. The library maintains a consistent overall AST shape, aiming to simplify client-side processing tasks.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to parse a CSS selector string into an AST, serialize the AST back to a string, and normalize the AST structure.

import { parse1, serialize, normalize } from 'parseley';
import { inspect } from 'node:util';

const str = 'div#id1 > .class2.class1[attr1]';

// Parse the CSS selector string into an AST
const ast = parse1(str);
console.log('Parsed AST:', inspect(ast, { breakLength: 45, depth: null }));

// Serialize the AST back into a CSS selector string
const serialized = serialize(ast);
console.log(`Serialized: '${serialized}'`);

// Normalize the AST (e.g., reorder simple selectors) and then serialize again
normalize(ast);
const normalized = serialize(ast);
console.log(`Normalized: '${normalized}'`);

view raw JSON →