CSS Selectors
CSS Selectors
The selector engine parses CSS selector text into structured form and evaluates it against DOM trees. It backs both direct queries and the cascade’s rule matching.
Running Selectors
select() evaluates a selector against a tree and returns matches; element_matches() tests a single element. Both accept standard selector syntax — type, class, id, attribute, and pseudo-class selectors, including compound and complex combinations.
Parsed Selector Structures
parse() produces a SelectorList of ComplexSelector and CompoundSelector entries built from TypeSelector, ClassSelector, IDSelector, AttributeSelector (with AttributeOperator), UniversalSelector, and Combinator parts.
Pseudo-Classes
Functional pseudo-classes are modelled explicitly: IsPseudoClass, WherePseudoClass, HasPseudoClass, ComplexNotPseudoClass, and structural nth-child variants via NthFilteredChildPseudoClass with NthArgument.
Specificity
specificity() computes the standard three-component tuple for a selector, and max_specificity() reduces a list; match() ties parsing and evaluation together. These are the same values the cascade uses, so query results and computed styles always agree.
Tips and Best Practices
- Use
element_matches()inside filters instead of re-runningselect()per element - Parse once and reuse the
SelectorListwhen the same selector runs against many trees - When a rule unexpectedly loses the cascade, compare
specificity()values directly
Common Issues
| Issue | Cause | Fix |
|---|---|---|
| Selector matches nothing | Syntax error in selector text | parse() raises via syntax_error — check the message |
| Equal-specificity ties resolve “wrong” | Order dependence | Later rules win ties; check rule order |
:is() vs :where() confusion | :where() contributes zero specificity | Choose per intended cascade weight |
FAQ
How do I test one element against a selector?
element_matches() — it returns a boolean without scanning the tree.
How is specificity calculated?
specificity() returns the standard (id, class, type) component tuple; :where() groups contribute zero.
Which pseudo-classes are supported?
The structured forms in the API: :is(), :where(), :has(), :not() with complex arguments, and nth-child-style structural selectors.
API Reference Summary
| Class/Method | Description |
|---|---|
select | Evaluate a selector against a tree |
element_matches | Test one element |
parse | Parse selector text into a SelectorList |
specificity | Compute the specificity tuple |
HasPseudoClass | Structured :has() form |
AttributeSelector | Attribute matcher with operators |