:has()
The :has()
CSS pseudo-class represents an element if any of the selectors passed as parameters (relative to the :scope
of the given element) match at least one element.
/* Selects any <a>, as long as it has an <img> element directly inside it */
let test = document.querySelector('a:has(> img)');
Syntax
:has( <forgiving-relative-selector-list> )
Description
The :has()
pseudo-class takes a relative selector list as an argument. In earlier revisions of the CSS Selectors Level 4 specification, :has
had a limitation that it couldn't be used within stylesheets. Instead, it could only be used with functions like document.querySelector()
; this was due to performance concerns. This limitation has been removed because no browser implemented it that way.
Examples
Matching <a> elements that directly contain an <img>
Matching <h1> elements that are followed by a <p>
Specifications
Specification |
---|
Selectors Level 4 # relational |
Browser compatibility
BCD tables only load in the browser