What is css-selector-parser?
The css-selector-parser npm package is a utility for parsing CSS selectors into an abstract syntax tree (AST). This can be useful for various applications such as CSS preprocessing, validation, and transformation.
What are css-selector-parser's main functionalities?
Parsing CSS Selectors
This feature allows you to parse a CSS selector string into an abstract syntax tree (AST). The example code demonstrates how to parse a complex CSS selector and output the resulting AST.
const { CssSelectorParser } = require('css-selector-parser');
const parser = new CssSelectorParser();
parser.registerNestingOperators('>', '+', '~');
parser.registerAttrEqualityMods('^', '$', '*', '~');
const ast = parser.parse('div.class[attr^="value"] > p');
console.log(JSON.stringify(ast, null, 2));
Customizing Parser Behavior
This feature allows you to customize the behavior of the parser by registering different nesting operators and attribute equality modifiers. The example code shows how to enable substitutes and register custom operators.
const { CssSelectorParser } = require('css-selector-parser');
const parser = new CssSelectorParser();
parser.registerNestingOperators('>', '+', '~');
parser.registerAttrEqualityMods('^', '$', '*', '~');
parser.enableSubstitutes();
const ast = parser.parse('div.class[attr^="value"] > p');
console.log(JSON.stringify(ast, null, 2));
Serializing AST to CSS Selector
This feature allows you to serialize an abstract syntax tree (AST) back into a CSS selector string. The example code demonstrates how to parse a CSS selector into an AST and then render it back to a string.
const { CssSelectorParser } = require('css-selector-parser');
const parser = new CssSelectorParser();
parser.registerNestingOperators('>', '+', '~');
parser.registerAttrEqualityMods('^', '$', '*', '~');
const ast = parser.parse('div.class[attr^="value"] > p');
const selector = parser.render(ast);
console.log(selector);
Other packages similar to css-selector-parser
postcss-selector-parser
PostCSS Selector Parser is a tool for parsing, transforming, and stringifying CSS selectors. It is more feature-rich and integrates well with the PostCSS ecosystem, making it suitable for more complex CSS processing tasks.
css-what
css-what is a CSS selector parser that is part of the Cheerio library. It is designed to be fast and efficient, making it a good choice for applications that require high performance.
csstree
CSSTree is a tool for parsing, walking, and generating CSS. It provides a comprehensive set of features for working with CSS, including a detailed AST and various utilities for manipulating CSS. It is more comprehensive compared to css-selector-parser.
css-selector-parser

A high-performance CSS selector parser with advanced features for modern web development.
Features
- 🚀 Fast and memory-efficient parsing for all CSS selectors
- 🌳 AST-based object model for programmatic manipulation
- 📊 Full compliance with all CSS selector specifications
- 🧪 Comprehensive test coverage
- 📚 Well-documented API with TypeScript support
- 🔄 Two-way conversion between CSS selectors and AST
- 🧩 Modular support for various CSS specifications
Supported CSS Selector Standards
Migration Guides
See Changelog for release details.
Installation
npm install css-selector-parser
yarn add css-selector-parser
pnpm add css-selector-parser
Usage
Parsing Selectors
import { createParser } from 'css-selector-parser';
const parse = createParser();
const selector = parse('a[href^="/"], .container:has(nav) > a[href]:nth-child(2)::before');
console.log(selector);
This produces an AST (Abstract Syntax Tree) output:
({
type: 'Selector',
rules: [
{
type: 'Rule',
items: [
{ type: 'TagName', name: 'a' },
{
type: 'Attribute',
name: 'href',
operator: '^=',
value: { type: 'String', value: '/' }
}
]
},
{
type: 'Rule',
items: [
{ type: 'ClassName', name: 'container' },
{
type: 'PseudoClass',
name: 'has',
argument: {
type: 'Selector',
rules: [
{
type: 'Rule',
items: [ { type: 'TagName', name: 'nav' } ]
}
]
}
}
],
nestedRule: {
type: 'Rule',
items: [
{ type: 'TagName', name: 'a' },
{ type: 'Attribute', name: 'href' },
{
type: 'PseudoClass',
name: 'nth-child',
argument: { type: 'Formula', a: 0, b: 2 }
},
{
type: 'PseudoElement',
name: 'before'
}
],
combinator: '>'
}
}
]
})
Building and Rendering Selectors
import { ast, render } from 'css-selector-parser';
const selector = ast.selector({
rules: [
ast.rule({
items: [
ast.tagName({name: 'a'}),
ast.attribute({name: 'href', operator: '^=', value: ast.string({value: '/'})})
]
}),
ast.rule({
items: [
ast.className({name: 'container'}),
ast.pseudoClass({
name: 'has',
argument: ast.selector({
rules: [ast.rule({items: [ast.tagName({name: 'nav'})]})]
})
})
],
nestedRule: ast.rule({
combinator: '>',
items: [
ast.tagName({name: 'a'}),
ast.attribute({name: 'href'}),
ast.pseudoClass({
name: 'nth-child',
argument: ast.formula({a: 0, b: 2})
}),
ast.pseudoElement({name: 'before'})
]
})
})
]
});
console.log(render(selector));
CSS Modules Support
CSS Modules are specifications that add new selectors or modify existing ones. This parser supports various CSS modules that can be included in your syntax definition:
import { createParser } from 'css-selector-parser';
const parse = createParser({
syntax: 'selectors-4',
modules: ['css-position-3', 'css-scoping-1']
});
Supported CSS Modules
css-position-1/2/3/4 | Position-related pseudo-classes |
css-scoping-1 | Shadow DOM selectors (:host , :host-context() , ::slotted() ) |
css-pseudo-4 | Modern pseudo-elements (::selection , ::backdrop , etc.) |
css-shadow-parts-1 | ::part() for styling shadow DOM components |
The latest
syntax automatically includes all modules marked as current specifications.
API Documentation
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT
Security Contact
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
If you find this project useful, please consider sponsoring the developer or supporting on Patreon.