---
title: "Queries on the live tree"
url: https://recursiveai.org/onehtml/docs/live-queries/
description: "Selector matching and element queries on a MutableDocument as it is, between commits. A script runtime calls matches, closest, querySelector[All] and…"
version: "1.8.0"
source: https://github.com/recursive-ai-oss/onehtml-csharp/blob/9213d47aed47f691bf05853759fd8e328a6a980e/docs/live-queries.md
---

# Queries on the live tree

Selector matching and element queries on a `MutableDocument` as it is, between commits. A script runtime calls `matches`, `closest`,
`querySelector[All]` and `getElementsBy*` many times per task and commits once per task, so none of these commits, builds a snapshot or
copies the tree. Everything here is an addition; snapshots and `Node` queries behave as before.

## 1. Where they run

`MutableNode.Matches`, `Closest`, `QuerySelector`, `QuerySelectorAll`, `GetElementsByTagName`, `GetElementsByTagNameNS`,
`GetElementsByClassName`, `GetElementById`, and `MutableDocument.GetElementsByName` and `GetElementById`.

- **Any tree.** The node may be in the document, in a detached subtree, in a document fragment (also a `template`'s content) or in a
  shadow root. Matching never depends on a snapshot containing the node. `Matches` and `Closest` are false/null for a non-element;
  `QuerySelector[All]` is defined for elements, documents, fragments and shadow roots (null/empty for other kinds).
- **Selectors** are Selectors Level 4 as for snapshots (`selectors.md`); the same matcher runs. A selector string is compiled once per
  document and cached by its text (512 entries, then the cache is cleared); pass a `SelectorList` to skip the lookup.
- **Errors.** An invalid or over-limit selector is `DomException` with `Kind == SyntaxError` (`Name` "SyntaxError"); the document is
  untouched. A released node is `StaleNode`. A null argument is `ArgumentNullException`. The selector is parsed (and may throw) before the
  node is examined, so `matches` on a text node with a bad selector still throws.
- **`:scope`** is the element itself for an element, the document element for a document, and nothing for a fragment or shadow root.
  `Closest` uses the element it was called on for every candidate.
- **Results.** `QuerySelectorAll` returns a new static `List<MutableNode>` (or appends to the list you pass); order is tree order.
  `getElementsBy*` return a live collection (section 3).

## 2. The live view

The matcher reads the mutable layer's own columns through a `Document` whose arena arrays *are* the working tree's arrays (slot-indexed),
so nothing is copied and no commit is needed:

- Node, attribute and character-data columns are shared. Attribute rows are stored as columns in the arena's layout; values live in the
  document's character pool (`ValueSide`), character data is flagged `DataSide`.
- A node's index in the view is its slot, so document order is **not** index order here; every walk follows the tree links.
- Side tables that snapshots build once (sibling positions, the generic id table, slot assignments, form groups) are dropped whenever
  `TreeVersion`, the slot count or a release changed, and rebuilt lazily by the selectors that need them.
  - `:first-child`, `:last-child`, `:only-child`, `:nth-*` and the `-of-type` forms: a single `Matches`/`Closest` walks the element's
    siblings (O(siblings), no table). A query over many elements (`QuerySelector[All]`) builds the table once for that version, so
    `li:nth-child(odd)` over a 20,000-item list is linear.
  - An element with no parent is its own only sibling (Selectors 4 §14.1), in both paths.
- **Ids.** `GetElementById` on a document, fragment or shadow root, and a selector whose only key is an id, use an id table per tree scope
  that the layer keeps current: built on first use for a scope, then updated on every link, unlink, `id` change and release (cost
  proportional to the inserted or removed subtree, only for scopes that have a table). With several elements holding the id,
  `GetElementById` returns the first in tree order (found by comparing positions, O(duplicates x depth)); a selector query on an id
  with duplicates scans instead, so it cannot become quadratic. Template contents and shadow roots are their own scopes.
- **Dead slots** (released nodes after the next commit) are reset to an empty, unlinked comment so tables over all slots never follow a
  stale pointer into a reused slot.
- Quirks mode is the document's. The view is for the writer thread only, like `MutableNode`.

## 3. Live collections

`LiveElementCollection` implements `IReadOnlyList<MutableNode>` and is the `HTMLCollection` of the element-by-name queries
(`GetElementsByName` stands for the live `NodeList` of `Document.getElementsByName`).

- **Choice: a live collection that caches and revalidates by version**, not a bare enumerator. It keeps its result array and the counters
  it was computed at: the document's structure counter (links, unlinks, releases) and, for the class and name filters, the version of that
  one attribute (`GetAttributeVersion`). A read whose counters still match returns the cached result: `Count`, the indexer, `GetItem`,
  `NamedItem` and the struct `Enumerator` allocate nothing. A read after a change walks the subtree once (no recursion), refills the
  same array, and bumps `Generation`. Text edits and unrelated attribute edits do not invalidate it.
- Matching follows DOM 4.9: `*` matches all; an HTML element of an HTML document is compared with the lower-cased name, other elements
  with the name as given; `GetElementsByTagNameNS` takes a namespace URI (`*` for any; null or empty matches nothing, since every element
  here has a namespace) and a local name; class tokens split on ASCII white space, ASCII case-insensitive in quirks mode, no tokens
  matches nothing; `GetElementsByName` matches HTML elements whose `name` attribute equals the value.
- A collection whose root was released is empty. `Generation` lets a caller cache wrappers per result. `NamedItem` follows HTML 3.1.5
  (id first, then `name` of HTML elements). The collection keeps only the root and the counters, so it is cheap to keep or to drop.
- The collection object itself is one small allocation per call; callers that want identity keep the object.

## 4. State the host feeds

The library sees no pointer, no URL and no registry, so the host supplies them on the document:

| Pseudo-class | Source |
|---|---|
| `:focus`, `:focus-within` | the focused element (`Focus.FocusedElement`; a released or disconnected focus reads as none) |
| `:focus-visible` | the focused element and `MutableDocument.FocusVisible` (default true) |
| `:hover` | `HoverElement` and its ancestors |
| `:active` | `ActiveElement` and its ancestors |
| `:target`, `:target-within` | `TargetElement` |
| `:checked`, `:disabled`, `:enabled`, `:indeterminate`, `:read-only`, `:read-write` | the attributes, replaced per element by `SetCheckedOverride`, `SetDisabledOverride`, `SetIndeterminateOverride` (the same rules as `FormStateOverrides`; `ClearFormStateOverrides`; an override dies with its element) |
| `:defined`, `:state(x)` | `CustomElementStates` (`ICustomElementStates`). With none, the document's own custom element state answers (the same as a snapshot of it): a valid custom element name with no definition is not defined, and `:state()` matches the states in `ElementInternals.States` |

Labels' controls (`HoverControl`, `ActiveControl`) are not derived. `:visited` never matches. The state setters are plain properties and do
not count as tree changes. A node of another document is `WrongDocument`.

## 5. Shadow roots

A query made from a node inside a shadow tree runs in that tree's scope (CSS Scoping 1 §3.2): the root's host is the contextual parent of
the tree's top-level elements, so `root.QuerySelector(":host > article")`, `:host(.c) p` and `:host-context(body) p` can match
(WPT `ParentNode-querySelector-host-pseudo-class.html`); the host is never a result, and `Closest` does not cross the root. A host
asked `host.Matches(":host")` from the document is false. `::slotted()` and `::part()` never match in queries (they are pseudo-elements).
Snapshot `Node.Matches` keeps its documented behaviour of never matching `:host` forms. `GetElementById` on a root sees only that root.

## 6. Cost

Per match step nothing is allocated; `Matches`, `Closest`, `QuerySelector` and `GetElementById` allocate 0 B in steady state for a
cached selector (test `Matching_a_cached_selector_allocates_nothing`). A query after an edit resets the view's tables in O(1) and pays for
a table only if the selector reads one.

## 7. Tests

- `dom/nodes/selectors.js` (the same 2,140 passing cases as the snapshot run, in the four contexts: document, element, detached
  element, fragment) and `Element-closest.html`, run through the live tree with and without a pending edit, asserting no commit happened.
- Translated: `ParentNode-querySelector-orphan-scope`, `-parent-context`, `-class-change`, `-attribute-change`, `-dupe-id`,
  `-host-pseudo-class`, `-shadowroot-nth-child`, `ParentNode-querySelectorAll-removed-elements`,
  `DocumentFragment-querySelectorAll-after-modification`, `DocumentFragment-getElementById`, `Document-getElementById`,
  `Element-getElementsByClassName`, `Document-getElementsByClassName` (liveness).
- Live and snapshot results equal over random edit sequences, uncommitted and after commit, for 20 selectors, ids, tag and class
  collections and detached subtrees.
- Not translated: the XML/XHTML pages, `createElementNS`/namespaced-element pages and tests that need script semantics (argument
  stringification, `HTMLCollection` prototypes, iframes); the library's namespaced `Attr` creation is outside this unit.
