Registry / serialization / css-selector-parser

css-selector-parser

JSON →
library3.3.0jsnpmunverified

css-selector-parser is a high-performance JavaScript/TypeScript library designed for parsing CSS selectors into a comprehensive Abstract Syntax Tree (AST). It provides an AST-based object model that enables programmatic manipulation, analysis, and transformation of selectors through its visitor pattern implementation. The library offers full compliance with a wide array of CSS selector specifications, including CSS1, CSS2, CSS3, and Selectors Level 4, with an additional "progressive" mode for handling unknown or future pseudo-classes and attributes. Currently at version 3.3.0, the package suggests an active development cycle, evidenced by its multiple migration guides for major versions. Key differentiators include its speed, memory efficiency, extensive TypeScript support for a well-documented API, and an interactive playground for real-time testing and visualization of AST outputs.

npm install css-selector-parser
INSTALL
IMPORT
SIG · CSS-SELECTOR-PARSE
C
css-selector-parser
serializationjavascriptv3.3.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createParser
import { createParser } from 'css-selector-parser';
const createParser = require('css-selector-parser').createParser;
The library is primarily designed for ESM consumption in modern environments. While `require` might work in some transpiled setups, `import` is the idiomatic way to use it since v3.
traverse
import { createParser, traverse } from 'css-selector-parser';
const { traverse } = require('css-selector-parser');
Used alongside `createParser` to implement the visitor pattern for AST analysis or transformation.
AST Node Types
import type { Selector, Rule, TagName, Attribute } from 'css-selector-parser';
import { Selector } from 'css-selector-parser/dist/ast';
Key interfaces like `Selector`, `Rule`, `Attribute`, `TagName`, etc., are exported directly for strong typing in TypeScript projects.

This quickstart demonstrates parsing a complex CSS selector into an AST and then traversing the AST to log specific node types like TagName and Attribute, showcasing basic library usage.

import { createParser, traverse } from 'css-selector-parser'; const parse = createParser(); const selectorString = 'a[href^="/"]::before, .container:has(nav) > a[href]:nth-child(2)'; const selectorAst = parse(selectorString); console.log('Parsed Selector AST:', JSON.stringify(selectorAst, null, 2)); // Example of AST traversal traverse(selectorAst, (node, context) => { if (node.type === 'TagName') { console.log(`Found TagName: ${node.name} at depth ${context.parents.length}`); } else if (node.type === 'Attribute') { console.log(`Found Attribute: ${node.name} with operator ${node.operator || 'none'}`); } });
Debug
Known issues
breakingUpgrading from versions 1.x or 2.x to 3.x introduced significant breaking changes in the API and the structure of the generated AST. Users must consult the `CHANGELOG.md` and dedicated migration guides for detailed information.
fix
Review the 'Migrating from 1.x to 3.x' and 'Migrating from 2.x to 3.x' sections in the `CHANGELOG.md` file to adapt your codebase to the new API and AST structure.
affects: >=3.0.0
breakingVersion 3+ of css-selector-parser is designed primarily for ES Modules (ESM). While older Node.js versions or CommonJS projects might attempt to use `require()`, this can lead to compatibility issues without proper transpilation or explicit ESM configuration.
fix
Configure your project to use ES Modules by adding `"type": "module"` to your `package.json` or by using `.mjs` file extensions for ESM files. Use `import` statements as shown in the documentation.
affects: >=3.0.0
gotchaUsing the `progressive` standard option can be a footgun. While it allows for parsing unknown pseudo-classes, pseudo-elements, and attribute case sensitivity modifiers, it means the parser will accept potentially invalid or non-standard CSS selectors without error, which might be undesirable for strict validation.
fix
For strict CSS compliance, explicitly specify a W3C standard (e.g., `css: 'selectors-4'`) when creating the parser: `createParser({ css: 'selectors-4' })`. Only use `progressive` if you intend to support experimental or custom syntax.
affects: >=1.0.0
Errors
Common errors & fixes
SyntaxError: Cannot use import statement outside a module
Attempting to use ES module `import` syntax in a CommonJS (CJS) module context, typically in a `.js` file without `"type": "module"` in `package.json` or in a `.cjs` file.
fix
Ensure your project is configured for ES Modules by adding `"type": "module"` to your `package.json`, or rename the file to `.mjs`. If you must use CommonJS, consider dynamic `import()` or transpile your code.
TypeError: (0 , css_selector_parser_1.createParser) is not a function
This error often occurs when trying to `require()` an ES Module-first package, or incorrectly destructuring its exports in a CommonJS context.
fix
Ensure your project is configured for ES Modules and use `import { createParser } from 'css-selector-parser';`. If you need to use CommonJS, consider using dynamic `import()`: `const { createParser } = await import('css-selector-parser');` (requires Node.js 14+).
Error: Selector parse error: Unexpected token at ...
The input CSS selector string is malformed, contains a syntax error, or uses a CSS feature not supported by the currently configured parsing standard (e.g., `css1`, `css2`, `selectors-3`, `selectors-4`).
fix
Review the problematic selector for syntax errors against W3C specifications. If the selector uses modern or experimental features, try configuring the parser with a higher compliance level or the `progressive` option: `createParser({ css: 'selectors-4' })` or `createParser({ css: 'progressive' })`.
Upgrade
Version history
3.3.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
6 hits · last 30 days
node
6
Resources
css-selector-parser — npm install css-selector-parser · libregistry