: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.
Code
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:
documentare 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
CSS Specificity CalculatorCalculate CSS selector specificity scores using the standard (a, b, c) notation. Enter any selector and see its inline, ID, class, and element contributions instantly.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.