JavaScript’s Element.matches()
method returns a Boolean value indicating whether the Element
would be selected by any of the specified CSS selectors.
Syntax
Element.matches(parameter);
Parameters
A string containing one or more CSS selectors to match the element against.
Return value
A Boolean value that is true
if the element matches any of the selectors and false
if the element does not match any of the selectors.
Exceptions
SyntaxError
DOMException
Thrown if the parameter cannot be parsed as a CSS selector list.
Examples
Here is an example of using the JavaScript matches()
method.
Consider the following lines of HTML:
<div id= "container">
<p class="selected">I like reading the JavaScript Guide.</p>
<p>I like vacuuming.</p>
</div>
How can we check which elements within the div
element have the class selected
?
One solution to this question is to select the div
element with the getElementById()
method, iterate over the element’s children, and use the matches()
method:
let container = document.getElementById('container');
let children = container.children;
for (const child of children) {
if (child.matches('.selected')) {
console.log(`”${child.textContent}” is selected.`);
}
}
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
matches() |
33 | 15 | 34 | 9 | 21 | 7 | 33 | 34 | 21 | 8 | 2.0 | 4.4 |