Introducing a new way to review your PRs.

Read the announcement

fb55 / css-select

a CSS selector compiler & engine

View on GitHub

17 documents · Updated Oct 26, 2026

docs / query-traversal

Query traversal

Query traversal turns a query context into an ordered set of candidate elements and applies a compiled selector to each candidate. It supports the selection APIs while keeping document order, scope rules, sibling behavior, and early-return behavior consistent. This page is a child of Query execution and caching and relates to Selector cache lifecycle.

Query entry flow

The public selection flow starts with a selector string or compiled predicate and ends with either all matching elements or the first match. The query layer prepares the starting context before traversal so the predicate sees the candidates required by the selector.

flowchart LR
    A[Query and input nodes] --> B[Compile query if needed]
    B --> C[Prepare context]
    C --> D[Enumerate candidates]
    D --> E[Reject non-elements]
    E --> F[Apply compiled predicate]
    F --> G[All matches]
    F --> H[First match or null]

The entry flow has these key contracts:

  • A single element is treated as a request to search its children. An array is normalized by removing duplicate nodes and nodes hidden by an ancestor in the same input set.
  • A query that needs following siblings expands the initial candidate set before traversal. The expansion preserves the input-before-sibling order expected by selection behavior.
  • A query that always fails returns an empty result for selectAll and null for selectOne without walking the tree.

References: src/index.ts• L82-110 src/index.ts• L113-149 src/index.ts• L161-198

Candidate enumeration

The traversal engine in src/…/querying.ts walks the prepared node arrays in depth-first order. It inspects each node once at its position, skips nodes that the adapter does not identify as elements, and then visits the element's children before continuing with later siblings.

The traversal rules define which nodes can affect selection results:

ConditionTraversal behavior
Node is not an elementSkip it and do not run the selector predicate.
Element matches the predicateAdd it to the all-match result or return it from the first-match search.
Element has childrenVisit its children before the next node in the current array.
HTML-style mode reaches a template elementMatch the template element itself but do not inspect its contents.
XML mode reaches a template elementInspect its contents like any other element.

This depth-first order makes selectAll return document order for a normal tree. It also makes selectOne return the first matching element in the same order without collecting later results.

References: src/…/querying.ts• L3-59 src/…/querying.ts• L62-118

Context and sibling boundaries

Context preparation controls the boundary of a search before candidate enumeration begins. It removes covered input nodes for array contexts and starts from the children of a single node, while sibling-aware selectors add the following element siblings that must also be considered.

The compiled query marks when following siblings are needed. This flag connects selector compilation to traversal: the query layer can widen the starting candidates without changing the normal depth-first walk or the predicate used for matching.

Relative selectors and :scope also depend on this boundary. Their compiled predicate receives the prepared context and can compare candidates with the intended scope rather than with an unrelated document root.

References: src/index.ts• L104-110 src/index.ts• L113-149 src/compile.ts• L83-117 src/types.ts• L147-164

Predicate filtering

Traversal only enumerates candidates. The compiled predicate decides whether each element satisfies the selector, including selector alternatives, combinators, attributes, and pseudo-selectors. This separation lets the same traversal support both string queries and precompiled queries.

Selector rules are arranged so inexpensive checks can reject candidates early and costly nested checks run later. A selector with multiple alternatives combines their results as an OR condition, so one matching alternative is enough to keep the candidate.

Nested selectors can start another search below the current element. For example, :has asks whether a qualifying descendant exists and can include following siblings when the nested selector requires them. That search uses the same first-match traversal and stops as soon as it finds evidence for the result.

References: src/compile.ts• L69-154 src/…/selectors.ts• L23-46 src/…/subselects.ts• L72-139

Result behavior

The selection APIs preserve a small set of observable result rules. selectAll returns every matching element in traversal order. selectOne returns the first matching element and stops the search. is evaluates one element directly and does not enumerate descendants.

The adapter supplies the tree operations that make these rules portable across DOM-like data models. It identifies elements, exposes children and siblings, removes covered input nodes, and can define node equality when object identity is not enough.

When a selector relies on reusable results, traversal remains responsible for candidate order and filtering. Cache reuse belongs to the compiled predicate and its cache policy; see Selector cache lifecycle.

References: src/index.ts• L161-218 src/types.ts• L14-78 src/types.ts• L185-198

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to context preparation must preserve the sibling expansion order and the removal of covered input nodes.
  • Changes to candidate walking must keep non-element filtering, depth-first order, and the HTML/XML template boundary aligned for both all-match and first-match APIs.
  • Changes to the compiled-query sibling flag must stay compatible with context preparation and nested :has searches.
  • Changes to adapter equality or subset removal can alter which candidates are searched and can silently change duplicate or ancestor results.
  • Changes to cache policy must not let reused predicate results outlive the document state they describe; see Selector cache lifecycle.

Important failure modes

TriggerConsequenceGuard
Following siblings are not added for a sibling-dependent queryA valid sibling match is never presented to the predicate.Keep the compiled sibling flag connected to context preparation.
A non-element node is passed to the predicateElement-only selector logic can receive an invalid node.Filter every candidate through the adapter's element check.
Template contents are traversed in non-XML modeHidden template content can appear in query results.Preserve the mode-specific template boundary.
Input subsets are not removedA query can search the same subtree more than once and produce duplicate work or results.Apply the adapter's subset removal before traversal.
Cached results are used after the document changesA matching decision can describe an old tree state.Disable or invalidate result reuse when the DOM is mutable between queries.

Key files

FileWhy to read it
src/index.tsDefines the selection entry flow, context preparation, sibling expansion, and public result behavior.
src/…/querying.tsDefines depth-first candidate enumeration, element filtering, template boundaries, and first-match stopping.
src/compile.tsShows how compiled predicates report sibling needs and combine selector alternatives.
src/…/subselects.tsShows how nested selector checks reuse traversal for existence tests such as :has.
src/types.tsDefines the adapter and compiled-query contracts that traversal depends on.