The Element.matches()
method returns true
if the element would be selected by the specified selector string; otherwise, returns false
.
var result = element.matches(selectorString);
result
holds the return value true
or false
.selectorString
is a string representing the selector to test.<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
.
SYNTAX_ERR
For browsers that do not support Element.matches()
or Element.matchesSelector()
, but carry support for document.querySelectorAll()
, a polyfill exists:
if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} return i > -1; }; }
However, given the practicality of supporting older browsers, the following should suffice for most (if not all) practical cases (i.e. IE9+ support).
if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector; }
Specification | Status | Comment |
---|---|---|
DOM The definition of 'Element.prototype.matches' in that specification. | Living Standard | Initial definition |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 34
|
Yes
|
34
|
9
|
21
|
7
|
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes
|
34
|
Yes
|
34
|
21
|
8
|
Yes
|
element.querySelector()
and element.closest()
.
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/element/matches