← 中文资源

简体中文版本

用 :scope 限定直接子元素

querySelectorAll 的裸选择器匹配任意深度的后代;「:scope > li」把匹配钉在当前节点的直接子元素上,换更深的根节点同样只看它的孩子。

阅读英文原文

实现说明

menu、fileItem 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。

常见问题

「用 :scope 限定直接子元素」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

核心语句

const fileItem = menu.querySelector(":scope > li");
const menu = document.querySelector("#menu");
<ul><li>New</li><li>Open</li></ul>
</li>
<li>Edit</li>
</ul>
`;

代码示例

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