Element: matches() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The matches()
method of the Element
interface tests whether the element would be selected by the specified CSS selector.
Syntax
js
matches(selectors)
Parameters
selectors
-
A string containing valid CSS selectors to test the
Element
against.
Return value
true
if the Element
matches the selectors
. Otherwise, false
.
Exceptions
SyntaxError
DOMException
-
Thrown if
selectors
cannot be parsed as a CSS selector list.
Examples
HTML
html
<ul id="birds">
<li>Orange-winged parrot</li>
<li class="endangered">Philippine eagle</li>
<li>Great white pelican</li>
</ul>
JavaScript
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
.
Specifications
Specification |
---|
DOM # ref-for-dom-element-matches① |
Browser compatibility
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
matches |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- Uses a non-standard name.
- Has more compatibility info.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
See also
- CSS selectors module
- Other
Element
methods that take selectors:Element.querySelector()
,Element.querySelectorAll()
, andelement.closest()
.