0
# PostCSS Selector Parser
1
2
PostCSS Selector Parser is a robust CSS selector parser that enables developers to parse, manipulate, and transform CSS selectors programmatically. It provides a comprehensive API for walking through selector ASTs, modifying selector components, and rebuilding selector strings with precise control over formatting and whitespace.
3
4
## Package Information
5
6
- **Package Name**: postcss-selector-parser
7
- **Package Type**: npm
8
- **Language**: JavaScript with TypeScript definitions
9
- **Installation**: `npm install postcss-selector-parser`
10
11
## Core Imports
12
13
```javascript
14
const parser = require('postcss-selector-parser');
15
```
16
17
For ESM:
18
19
```javascript
20
import parser from 'postcss-selector-parser';
21
```
22
23
With destructuring:
24
25
```javascript
26
const { attribute, className, combinator, comment, id, nesting, pseudo, root, selector, string, tag, universal } = require('postcss-selector-parser');
27
```
28
29
## Basic Usage
30
31
```javascript
32
const parser = require('postcss-selector-parser');
33
34
// Simple transformation
35
const transform = selectors => {
36
selectors.walk(selector => {
37
console.log(String(selector));
38
});
39
};
40
41
const transformed = parser(transform).processSync('h1, h2, h3');
42
43
// Normalize selector whitespace
44
const normalized = parser().processSync('h1, h2, h3', {lossless: false});
45
// Result: "h1,h2,h3"
46
47
// Async processing
48
const result = await parser().process('.class1, .class2');
49
```
50
51
## Architecture
52
53
PostCSS Selector Parser is built around several key components:
54
55
- **Parser Function**: Main entry point that creates processor instances with optional transform functions
56
- **Processor**: Handles parsing, transformation, and output generation with both sync and async methods
57
- **AST Nodes**: Comprehensive node types for all CSS selector components (tags, classes, IDs, attributes, etc.)
58
- **Node Constructors**: Factory functions for creating new AST nodes programmatically
59
- **Type Guards**: Runtime type checking functions for identifying node types
60
- **Container Interface**: Common methods for nodes that can contain children (Root, Selector, Pseudo)
61
62
## Capabilities
63
64
### Core Parser & Processor
65
66
Main parser function and processor class for parsing and transforming CSS selectors. Supports both synchronous and asynchronous processing with configurable options.
67
68
```javascript { .api }
69
function parser(transform?: ProcessorFn, options?: Options): Processor;
70
71
interface Processor {
72
res: Root;
73
result: string;
74
ast(selectors: Selectors, options?: Options): Promise<Root>;
75
astSync(selectors: Selectors, options?: Options): Root;
76
transform(selectors: Selectors, options?: Options): Promise<any>;
77
transformSync(selectors: Selectors, options?: Options): any;
78
process(selectors: Selectors, options?: Options): Promise<string>;
79
processSync(selectors: Selectors, options?: Options): string;
80
}
81
```
82
83
[Parser & Processor](./parser-processor.md)
84
85
### AST Node Creation
86
87
Factory functions for creating all types of CSS selector AST nodes. Essential for programmatically building selector structures.
88
89
```javascript { .api }
90
function attribute(props?: AttributeOptions): Attribute;
91
function className(props?: NamespaceOptions): ClassName;
92
function combinator(props?: NodeOptions): Combinator;
93
function comment(props?: NodeOptions): Comment;
94
function id(props?: NamespaceOptions): Identifier;
95
function nesting(props?: NodeOptions): Nesting;
96
function pseudo(props?: ContainerOptions): Pseudo;
97
function root(props?: ContainerOptions): Root;
98
function selector(props?: ContainerOptions): Selector;
99
function string(props?: NodeOptions): String;
100
function tag(props?: NamespaceOptions): Tag;
101
function universal(props?: NamespaceOptions): Universal;
102
```
103
104
[Node Constructors](./node-constructors.md)
105
106
### AST Node Manipulation
107
108
Base methods available on all AST nodes for manipulation, navigation, and tree modification. Includes specialized container methods for nodes that can have children.
109
110
```javascript { .api }
111
interface Base {
112
type: string;
113
parent: Container;
114
value: string;
115
remove(): Node;
116
replaceWith(...nodes: Node[]): Node;
117
next(): Node;
118
prev(): Node;
119
clone(opts?: object): this;
120
toString(): string;
121
}
122
123
interface Container extends Base {
124
nodes: Node[];
125
append(node: Node): this;
126
prepend(node: Node): this;
127
each(callback: (node: Node, index: number) => boolean | void): boolean | undefined;
128
walk(callback: (node: Node, index: number) => boolean | void): boolean | undefined;
129
}
130
```
131
132
[Node Manipulation](./node-manipulation.md)
133
134
### Type Guards & Validation
135
136
Runtime type checking functions for identifying and validating AST node types. Essential for safely working with the parsed AST.
137
138
```javascript { .api }
139
function isNode(node: any): boolean;
140
function isContainer(node: any): boolean;
141
function isNamespace(node: any): boolean;
142
function isRoot(node: any): boolean;
143
function isSelector(node: any): boolean;
144
function isAttribute(node: any): boolean;
145
function isClassName(node: any): boolean;
146
function isCombinator(node: any): boolean;
147
function isComment(node: any): boolean;
148
function isIdentifier(node: any): boolean;
149
function isNesting(node: any): boolean;
150
function isPseudo(node: any): boolean;
151
function isPseudoElement(node: any): boolean;
152
function isPseudoClass(node: any): boolean;
153
function isString(node: any): boolean;
154
function isTag(node: any): boolean;
155
function isUniversal(node: any): boolean;
156
```
157
158
[Type Guards](./type-guards.md)
159
160
### Node Type Constants
161
162
String constants for identifying AST node types. Available as properties on the main parser function.
163
164
```javascript { .api }
165
const TAG = "tag";
166
const STRING = "string";
167
const SELECTOR = "selector";
168
const ROOT = "root";
169
const PSEUDO = "pseudo";
170
const NESTING = "nesting";
171
const ID = "id";
172
const COMMENT = "comment";
173
const COMBINATOR = "combinator";
174
const CLASS = "class";
175
const ATTRIBUTE = "attribute";
176
const UNIVERSAL = "universal";
177
```
178
179
## Types
180
181
```javascript { .api }
182
type Selectors = string | PostCSSRuleNode;
183
type ProcessorFn = (root: Root) => any;
184
type SyncProcessor = ProcessorFn;
185
type AsyncProcessor = (root: Root) => Promise<any>;
186
187
interface ErrorOptions {
188
plugin?: string;
189
word?: string;
190
index?: number;
191
}
192
193
interface PostCSSRuleNode {
194
selector: string;
195
error(message: string, options?: ErrorOptions): Error;
196
}
197
198
interface Options {
199
lossless?: boolean;
200
updateSelector?: boolean;
201
}
202
203
interface NodeOptions {
204
value?: string;
205
spaces?: Spaces;
206
source?: NodeSource;
207
sourceIndex?: number;
208
}
209
210
interface ContainerOptions extends NodeOptions {
211
nodes?: Node[];
212
}
213
214
interface NamespaceOptions extends NodeOptions {
215
namespace?: string | true;
216
}
217
218
interface AttributeOptions extends NamespaceOptions {
219
attribute: string;
220
operator?: AttributeOperator;
221
insensitive?: boolean;
222
quoteMark?: QuoteMark;
223
quoted?: boolean; // deprecated, use quoteMark
224
raws?: AttributeRaws;
225
}
226
227
interface AttributeRaws {
228
attribute?: string;
229
operator?: string;
230
value?: string;
231
insensitive?: string;
232
unquoted?: string;
233
spaces?: {
234
before?: string;
235
after?: string;
236
attribute?: { before?: string; after?: string };
237
operator?: { before?: string; after?: string };
238
value?: { before?: string; after?: string };
239
};
240
}
241
242
type AttributeOperator = "=" | "~=" | "|=" | "^=" | "$=" | "*=";
243
type QuoteMark = '"' | "'" | null;
244
245
interface Spaces {
246
before: string;
247
after: string;
248
}
249
250
interface NodeSource {
251
start?: { line: number; column: number };
252
end?: { line: number; column: number };
253
}
254
```