Using matches() for Target Filtering
What you'll learn: How to use element.matches(selector) to filter delegated events so only specific descendant elements trigger your handler logic.
The Challenge with Basic Delegation
When you attach an event listener to a parent element, every bubbling event from any descendant reaches your handler. If you only care about certain child elements (like buttons with a specific class), you need a way to filter out the noise.
How matches() Solves This
The matches() method checks whether an element matches a CSS selector, returning true or false. Inside your delegated event handler, you use event.target.matches(selector) to test if the clicked element is one you care about.
The pattern:
parent.addEventListener('click', function(event) {
if (event.target.matches('.action-button')) {
// Only runs if clicked element has class "action-button"
console.log('Action button clicked!');
}
});
Think of It Like a Bouncer
Imagine a venue (parent element) where anyone can enter (events bubble up). The bouncer (your if statement with matches()) checks each person's wristband (CSS selector). Only guests with the right wristband get through to the VIP area (your actual handler code).
Why This Matters
Without filtering, you'd execute code for every click inside the parent, even on empty space or unwanted elements. The matches() method lets you write precise, efficient delegated handlers that respond only to specific targets.
Practical Example
document.querySelector('.menu').addEventListener('click', function(event) {
if (event.target.matches('.menu-item')) {
event.target.classList.toggle('active');
}
});
This handles clicks on any .menu-item inside .menu, ignoring clicks on the menu container itself or other children.
Key Takeaway: Use event.target.matches(selector) inside delegated event handlers to filter which descendant elements actually trigger your logic, making event delegation both powerful and precise.