← 中文资源

简体中文版本

:scope 把查询锚定在子树内

element.querySelector 传裸选择器仍会搜全文档:加上 :scope 前缀才锚定到当前元素子树,:scope > 再限定直接子代,避免子组件命名撞车导致的误匹配。

阅读英文原文

实现说明

演示用的数据放在这几个模块级绑定中:card、everyTag、inCard、directChildren。

使用要点

  • 这是浏览器侧代码——document 在 Node 里解析不到。
  • 每一步打印都带着自己的标签:document-wide tags:、tags inside card:、direct children only:。

常见问题

「:scope 把查询锚定在子树内」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

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

代码示例

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)'));