This article needs a technical review. How you can help.
The Element.matches()
method returns true
if the element would be selected by the specified selector string; otherwise, returns false
.
Several browsers implement this, prefixed, under the non-standard name matchesSelector()
.
SyntaxEdit
result = element.matches(selectorString)
result
holds the return valuetrue
orfalse
.selectorString
is a string representing the selector to test.
ExampleEdit
<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
.
ExceptionsEdit
SYNTAX_ERR
- The specified selector string is invalid.
PolyfillEdit
For browsers that do not support Element.matches()
or Element.matchesSelector()
, but carry support for document.querySelectorAll()
, a polyfill exists:
function matches(elm, selector) {
var matches = (elm.document || elm.ownerDocument).querySelectorAll(selector),
i = matches.length;
while (--i >= 0 && matches.item(i) !== elm) {}
return i > -1;
}
SpecificationEdit
Specification | Status | Comment |
---|---|---|
DOM The definition of 'Element.prototype.matches' in that specification. |
Living Standard | Initial definition |
Browser compatibilityEdit
[1] This feature was implemented with the non-standard name webkitMatchesSelector
.
[2] This feature was implemented with the non-standard name mozMatchesSelector
. Prior to Gecko 2.0, invalid selector strings caused false
to be returned instead of throwing an exception.
[3] This feature was implemented with the non-standard name msMatchesSelector
.
[4] This feature was implemented with the non-standard name oMatchesSelector
.