The matches()
method of the Element
interface tests whether the element would be selected by the specified CSS selector.
The matches()
method of the Element
interface tests whether the element would be selected by the specified CSS selector.
js
matches(selectors)
selectors
A string containing valid CSS selectors to test the Element
against.
true
if the Element
matches the selectors
. Otherwise, false
.
SyntaxError
DOMException
Thrown if selectors
cannot be parsed as a CSS selector list.
html
<ul id="birds"> <li>Orange-winged parrot</li> <li class="endangered">Philippine eagle</li> <li>Great white pelican</li> </ul>
js
const birds = document.querySelectorAll("li"); for (const bird of birds) { if (bird.matches(".endangered")) { console.log(`The ${bird.textContent} is endangered!`); } }
This will log "The Philippine eagle is endangered!" to the console, since the element has indeed a class
attribute with value endangered
.
Specification |
---|
DOM Standard # ref-for-dom-element-matches① |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
matches |
334 | 151212–79 | 44343.6["Before Firefox 4, invalid selector strings caused false to be returned instead of throwing an exception.", "See bug 1119718 for removal."] |
9 | 211511.5–15 | 85 | ≤374.4 | 3318 | 44344See bug 1119718 for removal. |
211411.5–14 | 84.2 | 2.01.0 |
Element
methods that take selectors: Element.querySelector()
, Element.querySelectorAll()
, and element.closest()
.
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Element/matches