querySelectorAll :has() Selects Parents
Use the :has() relational pseudo-class in querySelectorAll to select elements by their descendants, including negations like :not(:has(...)).
Code
// :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 —
documentwill 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.