Element.matches()
The matches()
method checks to see if the Element
would be selected by the provided selectorString
-- in other words -- checks if the element "is" the selector.
Syntax
var result = element.matches(selectorString);
Parameters
selectorString
is a string representing the selector to test.
Return value
result
is a boolean value.
Exceptions
-
SyntaxError
DOMException
-
Thrown if the specified selector string is invalid.
Example
<ul id="birds"> <li>Orange-winged parrot</li> <li class="endangered">Philippine eagle</li> <li>Great white pelican</li> </ul> <script type="text/javascript"> var birds = document.getElementsByTagName('li'); for (var i = 0; i < birds.length; i++) { if (birds[i].matches('.endangered')) { console.log('The ' + birds[i].textContent + ' is endangered!'); } } </script>
This will log "The Philippine eagle is endangered!" to the console, since the element has indeed a class
attribute with value endangered
.
Specifications
Specification |
---|
DOM Standard (DOM) # ref-for-dom-element-matches① |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
matches |
33
4
|
15
12
12
|
34
44
3.6
["Before Firefox 4, invalid selector strings caused false to be returned instead of throwing an exception.", "See bug 1119718 for removal."]
|
9 |
21
15
11.5-15
|
7
5
|
4.4
≤37
|
33
18
|
34
44
4
See bug 1119718 for removal.
|
21
14
11.5-14
|
8
4.2
|
2.0
1.0
|
See also
- The syntax of Selectors
- Other methods that take selectors:
element.querySelector()
andelement.closest()
.
© 2005–2021 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