The JavaScript matches() method
The matches() method tests whether an element matches a CSS selector and returns true or false. el.matches(".active") checks if el has the active class. It's commonly used in event delegation to confirm the clicked element is the kind you care about.
Overview
matches() answers a yes/no question: does this element match this CSS selector? el.matches("input[type=checkbox]"), el.matches(".btn.primary"), el.matches(":disabled") — anything you can write as a selector, you can test against a single element. It returns a clean boolean.
It pairs with closest() in the event-delegation toolkit. Where closest() climbs the tree to find a matching ancestor, matches() just tests the element in hand. In a delegated click handler you might write if (event.target.matches(".delete-btn")) to act only when a delete button itself was clicked.
It's also handy for filtering a collection by a complex condition, or for branching logic based on an element's state or type without reading individual properties. Think of it as bringing the full power of CSS selectors to a boolean check on one element.
Syntax
const yes = element.matches(selectors)
el.matches(".active") // true / false
el.matches("input[type=checkbox]")
if (e.target.matches(".delete")) { ... }
Parameters
The matches() method accepts the following parameters.
| Parameter | Description |
|---|---|
selectors |
A CSS selector string to test the element against. |
Example
<div id="box" style="font:15px system-ui">
<button class="primary">Primary</button>
<button>Plain</button>
</div>
<p id="out"></p>
<script>
document.getElementById('box').addEventListener('click', (e) => {
if (e.target.matches('button.primary')) {
document.getElementById('out').textContent = 'Primary button clicked!';
} else if (e.target.matches('button')) {
document.getElementById('out').textContent = 'A plain button.';
}
});
</script>
Best practices
- Use it in delegated handlers to confirm the target is the element you care about.
- Pair it with closest() —
matches()tests the element,closest()finds a matching ancestor. - Lean on full CSS selectors for state and type checks (
:checked,[type=email]). - It returns a boolean, so it reads naturally inside an
if.
Frequently asked questions
What does matches() do?
true if the element matches the given CSS selector, and false otherwise.What is the difference between matches() and closest()?
matches() tests only the element itself; closest() walks up the ancestors to find a match.How do I use matches() in event delegation?
if (event.target.matches(".btn")) to act only when the clicked element matches.Can matches() use pseudo-classes?
:checked, :disabled and :first-child work, making it great for state checks.