The matches() Method
You'll learn how to test whether an element matches a CSS selector without actually selecting or changing anything—perfect for conditional checks in your code.
What It Does
Sometimes you don't need to find an element—you already have one. Instead, you need to ask: "Does this element match a certain CSS selector?" The matches() method answers that question with a simple true or false.
Think of it like checking if someone fits a description without actually searching for them. You're looking at a person right in front of you and asking, "Are you wearing a red hat?"—not searching the room for people in red hats.
How It Works
Call matches() on an element and pass in a CSS selector string. It returns a boolean:
const button = document.getElementById('submit-btn');
// Does this button have the class 'disabled'?
if (button.matches('.disabled')) {
console.log('Button is disabled');
}
// Is this button inside a form?
if (button.matches('form button')) {
console.log('Button is inside a form');
}
// Multiple conditions
if (button.matches('.btn-primary, .btn-secondary')) {
console.log('Button is either primary or secondary');
}
Why It's Useful
This method shines in conditional logic, especially when handling events. You can check what kind of element triggered an event without multiple if-else chains:
document.addEventListener('click', (event) => {
if (event.target.matches('.delete-button')) {
// Handle delete
}
});
Key Takeaway: matches() lets you test if an element satisfies a CSS selector, returning true or false—ideal for conditional logic without selecting new elements.