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.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
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); // 2

How 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

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.