Sub topic 13
Using :has() from JavaScript
This chapter assumes you know the :has() syntax from the earlier chapters and the DOM methods querySelector, querySelectorAll, matches, and closest. You will use :has() in those methods and learn where the results differ from what you may expect.
Same selector, same engine
The selector APIs in JavaScript use the same selector parser as CSS. Any selector that works in a stylesheet works as a string argument, including :has().
const sections = document.querySelectorAll('section:has(> h2)');
const isCard = document.querySelector('.item').matches(':has(img)');The first line returns every section that has an h2 as a direct child. The second line returns true or false for one element. Before :has(), finding a parent from its child meant selecting the children and walking up with parentElement. A single selector string now replaces that loop.
The three methods
| Method | What `:has()` does there |
|---|---|
| `querySelectorAll(sel)` | Returns all matching elements, for example every list that contains a checked input |
| `matches(sel)` | Tests whether this element satisfies the condition |
| `closest(sel)` | Walks up from the element, including the element itself, and returns the first ancestor that satisfies the condition |
Here is a working example that uses all three.
<ul id="list">
<li class="item"><img src="a.png" alt="A"> First</li>
<li class="item">Second</li>
<li class="item"><input type="checkbox" checked> Third</li>
</ul>
<script>
const items = document.querySelectorAll('.item');
// querySelectorAll: items that contain an image
const withImages = document.querySelectorAll('.item:has(img)');
console.log(withImages.length); // 1
// matches: test one element
console.log(items[1].matches(':has(img)')); // false
// closest: from a checkbox, find the nearest item that has a checked input
const box = document.querySelector('input');
console.log(box.closest('li:has(:checked)').textContent.trim()); // "Third"
</script>Scoping with :scope
When you call element.querySelectorAll(...), the browser matches the selector against the whole document and then keeps only the descendants of element. The selector itself is not limited to that subtree. To anchor it to the element you called it on, use :scope.
const list = document.querySelector('#list');
// Only direct children of #list that contain an img
const direct = list.querySelectorAll(':scope > li:has(img)');Without :scope, a selector such as li:has(img) still works, but :scope makes your intent explicit. It also prevents surprises when the selector contains combinators that reach outside the element.
Matching is evaluated at call time
matches() and querySelectorAll() return a snapshot. If the DOM changes later, for example when a user checks a box, nothing notifies your script that a :has() condition has started or stopped matching. CSS updates automatically, but JavaScript has to ask again.
Listen for the event that causes the change and run the query then.
document.addEventListener('change', () => {
const checkedGroups = document.querySelectorAll('fieldset:has(:checked)');
console.log(`${checkedGroups.length} groups have a selection`);
});For changes that come from scripts rather than user input, use a MutationObserver and re-run the query in its callback.
Common errors
- An unsupported browser throws. If the browser does not recognize
:has(),querySelectorthrows aSyntaxError. It does not returnnull. CSS rules with unknown selectors are ignored silently, but the DOM methods are not. closest()includes the element itself.el.closest(':has(img)')returnselifelcontains an image. If you want only ancestors, start fromel.parentElement.- Pseudo-elements are still not allowed.
:has(::before)is invalid in JavaScript, as it is in CSS. - Nested
:has()is invalid. A selector such asdiv:has(p:has(a))fails in both CSS and JavaScript.
Feature detection
The CSS @supports selector() rule has a JavaScript counterpart, CSS.supports(). Use it to choose a code path before you run a query that might throw.
const hasSupport = CSS.supports('selector(:has(*))');
function cardsWithImages() {
if (hasSupport) {
return [...document.querySelectorAll('.card:has(img)')];
}
return [...document.querySelectorAll('.card')]
.filter((card) => card.querySelector('img'));
}The fallback does the same job with a plain filter, so the function returns the same result in every browser.
Exercise
A user clicks a button inside a div.panel. Write one line that returns that panel only if it contains at least one input:invalid, or null otherwise. Why does it throw an error in a browser without :has() support, and how can you avoid that?
Show answer
button.closest('.panel:has(input:invalid)'). The browser cannot parse the :has() selector, so the DOM method throws a SyntaxError instead of returning null. Check CSS.supports('selector(:has(*))') first, and in the fallback use button.closest('.panel') and test it with panel.querySelector('input:invalid').