querySelectorAll :has() Selects Parents

Use the :has() relational pseudo-class in querySelectorAll to select elements by their descendants, including negations like :not(:has(...)).

JavascriptData Integrity

Code

javascriptsnippet
16 lines
// :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);

How the code works

The code works entirely on top-level bindings: rows, clean, selected, invalidGroups.

Caveats

  • No third-party code is loaded at any point while this runs.
  • This is browser-side code — document will not resolve in Node.

Using it

Look for the late rows:, on-time rows:, checked rows: prefixes as the file runs; they connect each line to its step.

Key statements

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

Interactive Tools for This Topic

FAQ

Does querySelectorAll :has() Selects Parents 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.