← 中文资源

简体中文版本

querySelectorAll 用 :has() 选父级

在 querySelectorAll 里用 :has() 关系选择器按后代选中父元素:可配合 :not(:has(...)) 反选,也能向下穿透多层结构匹配。

阅读英文原文

实现说明

演示用的数据放在这几个模块级绑定中:rows、clean、selected、invalidGroups。

使用要点

  • 这是浏览器侧代码——document 在 Node 里解析不到。
  • 跑完文件,输出里会留下标记——late rows:、on-time rows:、checked rows:。

常见问题

「querySelectorAll 用 :has() 选父级」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

const selected = document.querySelectorAll('tr:has(input[type="checkbox"]:checked)');
const invalidGroups = document.querySelectorAll('fieldset:has(input:invalid)');
const clean = document.querySelectorAll('tr:not(:has(td.late))');

代码示例

// :has() matches elements by their descendants — the parent selector,
// usable anywhere a selector is: querySelectorAll, matches, closest
const rows = document.querySelectorAll('tr:has(td.late)');
console.log('late rows:', rows.length);

// :not(:has()) negates it: rows without the marker child
const clean = document.querySelectorAll('tr:not(:has(td.late))');
console.log('on-time rows:', clean.length);

// chain deeper structure: rows holding a checkbox that is checked
const selected = document.querySelectorAll('tr:has(input[type="checkbox"]:checked)');
console.log('checked rows:', selected.length);

// :has() also filters forms: fieldsets containing an invalid input
const invalidGroups = document.querySelectorAll('fieldset:has(input:invalid)');
console.log('invalid groups:', invalidGroups.length);