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-running select() per element
  • Parse once and reuse the SelectorList when the same selector runs against many trees
  • When a rule unexpectedly loses the cascade, compare specificity() values directly

Common Issues

IssueCauseFix
Selector matches nothingSyntax error in selector textparse() raises via syntax_error — check the message
Equal-specificity ties resolve “wrong”Order dependenceLater rules win ties; check rule order
:is() vs :where() confusion:where() contributes zero specificityChoose 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/MethodDescription
selectEvaluate a selector against a tree
element_matchesTest one element
parseParse selector text into a SelectorList
specificityCompute the specificity tuple
HasPseudoClassStructured :has() form
AttributeSelectorAttribute matcher with operators

See Also