:scope Keeps Queries Inside The Subtree

Relative selectors passed to element.querySelector still run against the whole document; prefixing :scope anchors them to the element the query was called on.

TypescriptData Integrity

Code

typescriptsnippet
15 lines
const card = document.querySelector('.card') as HTMLElement;

// A bare selector runs against the whole document: '.tag' matches every
// tag on the page, not only the ones inside this card.
const everyTag = document.querySelectorAll('.tag');

// :scope anchors each relative selector to the element the query ran on.
const inCard = card.querySelectorAll(':scope .tag');
const directChildren = card.querySelectorAll(':scope > .tag');

console.log('document-wide tags:', everyTag.length);
console.log('tags inside card:', inCard.length);
console.log('direct children only:', directChildren.length);
console.log('nested tags excluded by >:', directChildren.length <= inCard.length);
console.log('card contains a tag at all:', card.matches(':has(.tag)'));

Following the execution — :scope Keeps Queries Inside The Subtree

The file’s state is a handful of top-level bindings: card, everyTag, inCard, directChildren.

Caveats

  • Nothing arrives from a registry; the language ships every API used.
  • A browser is the runtime here: document are not available in Node.

Using it

The demo output is labeled (document-wide tags:, tags inside card:, direct children only:); each label names the call that printed it.

Key statements

const directChildren = card.querySelectorAll(':scope > .tag');
const card = document.querySelector('.card') as HTMLElement;
const inCard = card.querySelectorAll(':scope .tag');

Interactive Tools for This Topic

FAQ

Does :scope Keeps Queries Inside The Subtree run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.