Sub topic 13
Using :has() from JavaScript
This chapter assumes you know how :has() works in CSS. That means relative selectors such as :has(> img) and :has(+ p), and the restrictions on nesting and pseudo-elements. It also assumes you know the DOM methods querySelector and querySelectorAll, and how to attach an event listener. Here you will see that the selector engine behind CSS is the same one behind the DOM selector APIs, so :has() works in both places.
One selector engine, two uses
Browsers parse a selector string with the same grammar whether it appears in a stylesheet or in a call to querySelectorAll. You can therefore copy a :has() selector from your CSS into JavaScript and get the same matches. Four methods accept selector strings:
| Method | Called on | Returns | What `:has()` lets you do |
|---|---|---|---|
| `querySelector(sel)` | document or element | first matching descendant, or `null` | Find the first parent-like element that contains something |
| `querySelectorAll(sel)` | document or element | static `NodeList` of all matching descendants | Collect every element that contains something |
| `matches(sel)` | element | `true` or `false` | Test whether the element contains something |
| `closest(sel)` | element | nearest matching ancestor or the element itself, or `null` | Walk up to the nearest ancestor that contains something |
Before :has(), finding a parent by what it contained meant selecting the child and then reading child.parentElement. Now a single selector expresses the condition.
// All sections that have an h2 as a direct child
const sections = document.querySelectorAll('section:has(> h2)');
// Does this item contain an image anywhere inside it?
const isCard = document.querySelector('.item').matches(':has(img)');The first line returns a static NodeList. It is a snapshot, so elements added later do not appear in it. If the DOM changes, call querySelectorAll again.
Finding elements by what they contain
querySelector and querySelectorAll return the element that carries the :has(), not the element inside it. That is the difference from a plain descendant selector. Compare these two:
// Returns the <img> elements inside cards
const images = document.querySelectorAll('.card img');
// Returns the .card elements that contain an <img>
const cardsWithImages = document.querySelectorAll('.card:has(img)');Use the second form when you need to act on the container. For example, you can add a data attribute to each card that contains an image:
document.querySelectorAll('.card:has(img)').forEach((card) => {
card.dataset.media = 'image';
});This pattern is useful when a styling decision is better handled in CSS but you also need a hook for analytics or tests.
Sibling and child forms work too
All relative combinators are allowed in the argument:
// Headings immediately followed by a paragraph
const leadHeadings = document.querySelectorAll('h2:has(+ p)');
// Headings that have a list somewhere after them among their siblings
const listHeadings = document.querySelectorAll('h2:has(~ ul)');
// Lists with at least four direct items
const longLists = document.querySelectorAll('ul:has(> li:nth-child(4))');The last line is the quantity query from the CSS chapter. In JavaScript you could also check list.children.length >= 4. The selector form is shorter when you want a whole group of lists at once, and the property form is faster to read when you already hold one list.
Testing a single element with matches()
matches() answers a yes-or-no question about an element you already have. It is the natural fit inside event handlers.
const form = document.querySelector('form');
form.addEventListener('focusin', (event) => {
const field = event.target.closest('.field');
if (field && field.matches(':has(input:invalid)')) {
field.dataset.needsAttention = 'true';
}
});Here closest('.field') finds the wrapper of the focused input. Then matches(':has(input:invalid)') asks whether that wrapper currently contains an invalid input. The answer reflects the live state of the DOM at the moment you call it.
Walking up with closest()
closest() starts at the element itself, then checks each ancestor. Put :has() in its argument to find the nearest ancestor that satisfies a content condition:
document.addEventListener('click', (event) => {
const group = event.target.closest('fieldset:has(input[type="radio"])');
if (group) {
console.log('Clicked inside a radio group:', group.id);
}
});Two details matter here:
closest()can return the element itself. Ifevent.targetis afieldsetthat contains a radio input, it matches.- The
:has()condition applies to each candidate. Afieldsetwith no radio input is skipped, and the search continues upward.
Scoping with :scope
When you call element.querySelectorAll(selector), the browser matches the selector against the whole document and then keeps only the results that are descendants of element. The consequence for :has() is that the argument is not confined to the element. The result elements must be inside element, but a sibling relationship in the argument can point at nodes outside it only if the subject itself is inside.
To anchor a selector to the element you called it on, use :scope. It refers to that element.
const list = document.querySelector('#menu');
// Direct children of #menu that contain a link
const itemsWithLinks = list.querySelectorAll(':scope > li:has(> a)');Without :scope, the selector > li would be invalid, because a bare leading combinator is not allowed outside :has(). Inside :has(), a leading combinator is relative to the subject, so :has(> a) works without :scope.
Invalid selectors throw
The argument of :has() is unforgiving. If any part of the argument list is invalid, the whole selector is invalid. In CSS, the browser drops the rule. In JavaScript, the selector APIs throw a SyntaxError DOMException.
This matters in two situations:
- A browser that does not support
:has()throws on every selector that contains it. - A typo, or a forbidden construct such as a pseudo-element or a nested
:has(), throws in every browser.
try {
document.querySelector('.card:has(img::before)'); // pseudo-element is not allowed
} catch (error) {
console.log(error.name); // "SyntaxError"
}A CSS rule with the same selector would be ignored without any message. A thrown error in JavaScript is easier to notice, but it stops your script unless you catch it.
Feature detection
Use CSS.supports() with the selector() function. It is the JavaScript counterpart of @supports selector() in CSS.
const supportsHas = CSS.supports('selector(:has(*))');
function cardsWithImages(root = document) {
if (supportsHas) {
return Array.from(root.querySelectorAll('.card:has(img)'));
}
// Fallback: find images, then climb to their card
const cards = new Set();
root.querySelectorAll('.card img').forEach((img) => {
const card = img.closest('.card');
if (card) cards.add(card);
});
return Array.from(cards);
}The fallback produces the same set of cards without :has(). The Set removes duplicates when a card holds several images. Note that the fallback matches img at any depth, the same as :has(img).
Choosing between JavaScript and CSS
Many tasks that once needed JavaScript can now be expressed in CSS. Do not reach for querySelectorAll(':has(...)') just to toggle a class when a CSS rule would do the same thing without code. Use the following flow to decide.
Good reasons to use JavaScript with :has():
- You need to run logic, such as disabling a button, sending an event, or setting
aria-*attributes. - You need the list of matching elements, for example to count them.
- You are writing tests that assert which elements match a selector.
A complete example: form summary
This example combines the earlier parts. A form shows how many fields are invalid, and the submit button is disabled until none are. The HTML:
<form id="signup" novalidate>
<div class="field">
<label for="email">Email</label>
<input id="email" type="email" required>
</div>
<div class="field">
<label for="name">Name</label>
<input id="name" type="text" required minlength="2">
</div>
<p id="summary" aria-live="polite"></p>
<button type="submit" id="send" disabled>Send</button>
</form>The script:
const form = document.querySelector('#signup');
const summary = document.querySelector('#summary');
const send = document.querySelector('#send');
function refresh() {
const bad = form.querySelectorAll('.field:has(input:invalid)');
summary.textContent = bad.length === 0
? 'All fields look good.'
: `${bad.length} field(s) need attention.`;
send.disabled = bad.length > 0;
}
form.addEventListener('input', refresh);
refresh();Each time the user types, refresh() asks the selector engine which .field wrappers currently contain an invalid input. You do not track state yourself. The DOM and the browser's validation are the single source of truth. Because novalidate is set, the browser does not show its own bubbles, so you can style the wrappers with the CSS rule .field:has(input:invalid:not(:placeholder-shown)) from an earlier chapter if you add placeholders.
Performance and common mistakes
querySelectorAllruns the selector across the whole subtree each time you call it. Call it on a narrow root such asformrather thandocumentwhen you can.- Avoid calling it on every
mousemoveorscrollevent. Use it in input, click, or change handlers, or throttle the calls. - The result of
querySelectorAlldoes not update. If you cache it, refresh the cache after the DOM changes. - Do not expect an event when a
:has()condition starts or stops matching. The browser has no such event. Listen for the underlying events instead, such asinput,change, or aMutationObserveron the subtree. - A selector that works in a stylesheet works in JavaScript, with one exception. Pseudo-elements are never valid inside
:has()in either place.
Exercise
A page has <ul id="nav"> whose li children sometimes hold a nested ul. Write JavaScript that returns only the direct li children of #nav that contain a nested ul as a direct child, and explain why :scope is needed.
Show answer
Use document.querySelector('#nav').querySelectorAll(':scope > li:has(> ul)'). :scope refers to #nav, the element the method was called on, so > li selects only its direct children. Without :scope, a bare leading > is invalid outside :has() and would throw a SyntaxError. The :has(> ul) part keeps only the li elements that have a ul as a direct child.
Exercise
Your script calls document.querySelector('.card:has(img)') and a user on an older browser reports that the whole script stops working. What is happening, and how would you fix it?
Show answer
A browser without :has() support treats the selector as invalid, so querySelector throws a SyntaxError and stops the script. Check support first with CSS.supports('selector(:has(*))'). If it returns false, use a fallback such as selecting .card img and calling closest('.card') on each image. Wrapping the call in try/catch is a second safeguard.