Scoping querySelectorAll With :scope
querySelectorAll(':scope > li') pins matching to direct children of the node, while a bare selector keeps matching descendants at every nesting depth.
Code
document.body.innerHTML = `
<ul id="menu">
<li>File
<ul><li>New</li><li>Open</li></ul>
</li>
<li>Edit</li>
</ul>
`;
const menu = document.querySelector("#menu");
// A bare selector matches descendants at any depth
console.log(menu.querySelectorAll("li").length); // 4
// ":scope > li" pins matching to direct children only
console.log(menu.querySelectorAll(":scope > li").length); // 2
// From a deeper root, :scope means "children of this node"
const fileItem = menu.querySelector(":scope > li");
console.log(fileItem.querySelectorAll(":scope > ul > li").length); // 2How it works
Top-level bindings menu, fileItem hold the demo state — nothing sits inside a function scope.
Watch out for
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Statements that matter
const fileItem = menu.querySelector(":scope > li");
const menu = document.querySelector("#menu");
<ul><li>New</li><li>Open</li></ul>
</li>
<li>Edit</li>
</ul>
`;
Interactive Tools for This Topic
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 Scoping querySelectorAll With :scope 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.