web api instance method
Element: matches() method
The matches() method of the Element interface tests whether the element would be selected by the specified CSS selector.
Syntax
matches(selectors)
Parameters
selectors- : A string containing valid CSS selectors to test the
Elementagainst.
- : A string containing valid CSS selectors to test the
Return value
true if the Element matches the selectors. Otherwise, false.
Exceptions
SyntaxErrorDOMException- : Thrown if
selectorscannot be parsed as a CSS selector list.
- : Thrown if
Examples
HTML
<ul id="birds">
<li>Orange-winged parrot</li>
<li class="endangered">Philippine eagle</li>
<li>Great white pelican</li>
</ul>
JavaScript
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
SpecificationsStandards references are available on the canonical MDN page.
Browser compatibility
Browser compatibilityCompatibility data is available on the canonical MDN page.
See also
- CSS selectors module
- Other
Elementmethods that take selectors:querySelector(),querySelectorAll(), andclosest().