skip to content

html, css, and dom · lesson 2 of 8 · sources checked 2026-11-20

selectors and the limits of the dom

This lesson shows a selector that survives a change of class names, and three boundaries of the page that a selector cannot cross.

status of this lesson: documented in my test system

purpose

A selector finds elements in a DOM (Document Object Model) tree. A selector on a generated class name breaks at the next release of the site. Three parts of a page are also out of the reach of a selector from the main document.

objectives

  1. Write a selector that survives a change of CSS class names.
  2. Explain why a selector cannot cross a shadow root, a cross-origin iframe, or an isolated world.
  3. Describe the method that reads a value across each of the three boundaries.
  4. Record the resolution state of a read apart from its value.

new terms

selector
An expression that finds elements in a DOM tree.
structural selector
A selector that uses the element structure, not class names.
shadow root
A separate DOM subtree that a normal selector from the main document cannot enter.
isolated world
A script context that shares the DOM with the page but not the page's global variables.
WebDriver BiDi
The W3C bidirectional browser automation protocol with events.
realm
A separate JavaScript global environment, for example an iframe or a worker.
driver
Software that controls an unmodified browser through a protocol.
verdict
The result that a check gives. The sentence names the check: the oracle, a detector test page, a detection product, or a platform.
resolution state
A record of if a selector found an element, kept apart from the value that the element holds.

how it works

A selector names an element by its tag, its class, its other markup values, or its place in the tree. A site can make its class names at build time, so a class name can change at each release.

structure, not class names

A structural selector uses the element structure, not class names. Selectors Level 4 defines the relational pseudo-class :has(). For example, a:has(> img) finds only the a elements with an img child W3C, source 1.

The same form finds a result link in a list: a:has(> h3). It finds an anchor with an h3 child. A release that changes the class t-x7 to t-k2 breaks the selector a.t-x7. It does not break a:has(> h3).

estimate, not measured A structural selector breaks less often than a class selector, but a change of the layout also breaks it. This course has no measurement of the break rate of real pages.

three boundaries

A selector from the main document finds elements only in the tree of that document. Three parts of a page are outside that tree. For example, a search box in a widget can be in each of them:

  • A shadow root. document.querySelectorAll() does not find the elements in a shadow tree MDN, source 2. In the mode closed, the property shadowRoot of the host gives null. The same page says that this mode is not a strong security control. A browser extension can get around it.
  • An iframe. The HTML Standard states that the iframe element represents its own content navigable, with its own document WHATWG, source 3. A selector of the main document does not enter it. An iframe can come from a different scheme, host, or port. Then a script of the main document also cannot read its document.
  • An isolated world. A script in it shares the DOM with the page, but not the global variables of the page.

In WebDriver BiDi, an automation script can run in a sandbox, which is an isolated world. Each sandbox is a unique ECMAScript realm, and it gets to the DOM objects of the page through proxy objects W3C, source 4. The purpose is a script that can touch the DOM and does not see the changes that page scripts make to the DOM APIs.

the method for each boundary

Each boundary has its own method:

  • Shadow root: query from the shadowRoot of the host. This works only in the mode open.
  • Cross-origin iframe: use the list of iframes of the driver, and run the query in that iframe.
  • Isolated world: read a DOM element, not a global. For example, the page writes its state into an element with the id app-status, and the isolated script reads that element.

A widget can write its result into a hidden input of the main document. Then a read of that input is simpler than a query into the iframe of the widget.

record the resolution state

The verdict code of the benchmark platform, my test system, returns two fields for each read.

One field is the value of the element. The other field is the resolution state, which records if the selector found an element. A read with no resolution state gives the same empty value for "no element" and for "an element with no text".

These two cases are different results. "No element" can mean a change of the page, a block, or a selector boundary. "An element with no text" can mean an empty field. Thus a check that sees only the value can record a fail where the correct result is inconclusive.

the two sides

automation sidedetection side
A structural selector costs less maintenance than a class selector. A read with no resolution state gives the same value for "no element" and for "empty element".Changes of class names, shadow roots, and parts of the page that different teams build raise the cost of collection. They also raise the cost of the tests of the site.

design decisions

optiongaincostwhen it is correct
A class selectorShort and fast to writeIt breaks when the site makes new class namesClass names that do not change between releases
A structural selectorIt survives a change of class namesIt breaks when the structure changesPages with generated class names
A selector on a data-test value or a label textIt follows the meaning of the elementThe site can change the text or remove the valuePages with stable test values or labels
A read of a DOM element from an isolated worldThe page cannot change the code of the readThe read cannot see the page globalsEach read of the page state
A read with a resolution state"No element" and "empty value" stay apartOne more field in each recordEach read

diagram

three boundaries that a selector from the main document cannot cross

  1. Main documentA selector finds each element of this treepass
  2. Shadow rootNot found from the main document. Method: query from the shadowRoot of the host in open mode. A closed root gives null.fail
  3. Cross-origin iframeNot found from the main document. Method: the list of iframes of the driver, and a query in that iframe.fail
  4. Isolated worldShares the DOM but not the page globals. Method: read a DOM element, not a global.fail

Record the resolution state of each readno result

Each boundary has its own method, and each read records if it found its element.source: My model of the selector boundaries and the method for each one

code example

The first example reads a value with its resolution state. It compares a class selector with a structural selector on four versions of a synthetic page.

example The trees and the class names are synthetic.

m05-x04-resolve.tstypescript

Read a value with a class selector and with a structural selector, and return the resolution state of each read apart from its value.

import { readFileSync } from "node:fs";

// A synthetic DOM tree in JSON: { tag, cls?, text?, children? }. No browser and no package.
type Node = { tag: string; cls?: string; text?: string; children?: Node[] };
type Read = { state: "found"; value: string } | { state: "not-found" };

function all(n: Node, out: Node[] = []): Node[] {
  out.push(n);
  for (const c of n.children ?? []) all(c, out);
  return out;
}

function text(n: Node): string {
  return [n.text ?? "", ...(n.children ?? []).map(text)].join("").trim();
}

// Class selector, as "a.t-x7": it depends on a generated class name.
const byClass = (n: Node) => n.tag === "a" && n.cls === "t-x7";
// Structural selector, as "a:has(> h3)": an anchor with an h3 child.
const byStructure = (n: Node) => n.tag === "a" && (n.children ?? []).some((c) => c.tag === "h3");

function read(root: Node, match: (n: Node) => boolean): Read {
  const hit = all(root).find(match);
  // Keep "no element" apart from "an element with no text".
  return hit ? { state: "found", value: text(hit) } : { state: "not-found" };
}

const show = (r: Read) => (r.state === "found" ? `found "${r.value}"` : "not-found");
const pages: Record<string, Node> = JSON.parse(readFileSync(process.argv[2], "utf8"));
for (const [name, root] of Object.entries(pages)) {
  console.log(`${name}: class ${show(read(root, byClass))}; structure ${show(read(root, byStructure))}`);
}

output

One line for each page version: the result of the class selector and of the structural selector, as found with the value, or not-found.

v1: class found "Blue cup"; structure found "Blue cup"
v2: class not-found; structure found "Blue cup"
v3: class not-found; structure found ""
v4: class not-found; structure not-found

I ran the code with the Node runtime and the flag --experimental-strip-types, on four synthetic versions of one page:

  • Version v1 has an anchor with the class t-x7 and an h3 child with the text "Blue cup".
  • Version v2 has the same anchor with the new class t-k2.
  • Version v3 has the anchor with the class t-k2 and an empty h3.
  • Version v4 has no anchor. It has only the text "No results".

The structural selector survives the new class. In v3 and v4, the value is empty or missing, but the resolution state shows which case occurs.

The second example simulates two script worlds that share one DOM. It reads a page global and a DOM element from the isolated world. It reads again with a timer until it finds the value or a limit ends.

example The two worlds are plain objects. The code is a simulation, not a browser.

m05-x05-worlds.mjsjavascript

Simulate a page world and an isolated world that share one DOM. Read a global and a DOM element from the isolated world with a portable poll.

// A simulation of two script worlds that share one document. No browser and no package.
// In a browser, the page world and an isolated world have different globals, but one DOM.

const elements = new Map(); // The shared DOM: id -> { textContent }.
const sharedDocument = { getElementById: (id) => elements.get(id) ?? null };

const pageWorld = { document: sharedDocument, appState: undefined };
const isolatedWorld = { document: sharedDocument }; // No access to pageWorld globals.

// The page script: after 150 ms it sets a global and writes the same value into the DOM.
setTimeout(() => {
  pageWorld.appState = { status: "ready" };
  elements.set("app-status", { textContent: "ready" });
}, 150);

// A portable poll: only setTimeout and a Promise, no wait function of a driver.
function poll(check, { intervalMs = 50, timeoutMs = 1000 } = {}) {
  const start = Date.now();
  return new Promise((resolve) => {
    const tick = () => {
      const value = check();
      if (value !== null) return resolve({ state: "found", value });
      if (Date.now() - start >= timeoutMs) return resolve({ state: "not-found" });
      setTimeout(tick, intervalMs);
    };
    tick();
  });
}

// Read 1: a global from the isolated world. The isolated world has no such global.
const globalRead = await poll(() => isolatedWorld.appState?.status ?? null, { timeoutMs: 300 });
console.log(`global read from the isolated world: ${globalRead.state}`);

// Read 2: the DOM element from the isolated world. The two worlds share the DOM.
const domRead = await poll(() => isolatedWorld.document.getElementById("app-status")?.textContent ?? null);
console.log(`DOM read from the isolated world: ${domRead.state}, value "${domRead.value}"`);

output

Two lines: the result of the global read and the result of the DOM read, each with its resolution state.

global read from the isolated world: not-found
DOM read from the isolated world: found, value "ready"

I ran the code with Node and no argument. The page script sets its global and its DOM element after 150 ms. The global read stops at its limit of 300 ms with not-found. The DOM read finds the element.

failure modes

problemcausecorrection
A selector finds nothing after a release of the site.The selector uses a generated class name.Use a structural selector, a data-test value, or a label text.
A stored fail and a stored inconclusive look the same.The read returns only the value, with no resolution state.Return the value and the resolution state of each read.
A read of a page global returns nothing.The read runs in an isolated world, which does not see the page globals.Read a DOM element, because the two worlds share the DOM.
A query finds no element of a widget.The widget is in a cross-origin iframe or in a closed shadow root.Read a hidden input that the widget writes, or use the list of iframes of the driver.
A read finds nothing, because the page writes the value later.The read runs one time only.Read again with a timer and a limit, and record not-found at the limit.

check questions

  1. A site changes its generated class names at each release. A result link is an anchor with an h3 child. Which selector survives the next release?

    1. A selector on the class name of the anchor
    2. A selector for an anchor with an h3 child
    3. A selector on the class name of the h3 element
    answer

    b. A selector for an anchor with an h3 child

    A selector for an anchor with an h3 child uses the element structure, not a class name. A new class name does not break it. A change of the structure can break it.

  2. Explain why a selector of the main document cannot find an element inside a shadow root, a cross-origin iframe, or an isolated world.

    sample answer

    A selector of the main document finds elements only in the tree of that document. A shadow root is a separate subtree, and the querySelectorAll method of the document does not enter it. An iframe has its own document, and a script of the main document cannot read the document of a cross-origin iframe. An isolated world shares the DOM but not the page globals. Thus a read of a page global gives nothing there.

  3. Describe the method that reads a value across each of the three boundaries.

    sample answer

    For a shadow root in the mode open, query from the shadowRoot of the host. A closed root gives null. For a cross-origin iframe, use the list of iframes of the driver, and run the query in that iframe. Or read a hidden input that the widget writes. For an isolated world, read a DOM element, not a page global.

  4. A read gives an empty value. What must the record also hold, so that a later check can give the correct result?

    1. The resolution state: found or not-found
    2. Only the time of the read
    3. Nothing more, because an empty value is a fail
    answer

    a. The resolution state: found or not-found

    An empty value can come from no element or from an element with no text. The resolution state keeps the two cases apart, so the check can give inconclusive and not fail.

exercise

exercise Do this task in your own lab, with synthetic data only. Do not send a request to a site.

  1. Save the first code example in an empty folder of your lab.
  2. Write a JSON file with three synthetic page versions.
  3. Make version A with an anchor of the class t-x7 and an h3 child with the text "Green pot".
  4. Make version B with the same anchor, the class p-91, and the same h3.
  5. Make version C with the anchor of the class p-91 and a p child in place of the h3.
  6. Run the code with Node, the flag --experimental-strip-types, and the file.
  7. Record the two results for each version.
  8. Write which change breaks each selector.
sample answer

This sample answer uses the three synthetic versions only.

Version A gives "found" for both selectors, with the value "Green pot". Version B gives not-found for the class selector and "found" for the structural selector. Version C gives not-found for both selectors.

The new class name breaks the class selector. The change of the structure, a p in place of the h3, breaks the structural selector. The resolution state shows that the element is missing, not empty.

sources

  1. Selectors Level 4, W3C, draft, read 2026-11-20
  2. Using shadow DOM, MDN, documentation, read 2026-11-20
  3. HTML Standard, embedded content, WHATWG, standard, read 2026-11-20
  4. WebDriver BiDi, W3C, draft, read 2026-11-20
  5. Benchmark platform, code (my test system): the read that returns the value and the resolution state, 2026-11 (not public).
  6. My model of the selector boundaries and the method for each one, 2026-11 (not public).