Beyond basic selection, **closest()** traverses up the DOM tree to find the nearest ancestor matching a selector — essential for event delegation. **matches()** tests if an element matches a selector — useful in event handlers. **within-element queries** scope selection to a subtree.
1Understanding DOM Selection Methods
Beyond basic selection, closest() traverses up the DOM tree to find the nearest ancestor matching a selector — essential for event delegation. matches() tests if an element matches a selector — useful in event handlers. within-element queries scope selection to a subtree.
Use event delegation: attach one listener to a parent, use event.target.closest('.item') to find the clicked item. Much more efficient than attaching listeners to each item.
// Event delegation with closest()
document.querySelector('#list').addEventListener('click', (e) => {
const item = e.target.closest('.list-item');
if (!item) return; // clicked outside any item
console.log('Clicked:', item.dataset.id);
});2Practical Example
Here is a real-world application of DOM Selection Methods showing how it is used in production JavaScript code.
// matches() for filtering events
document.addEventListener('click', (e) => {
if (e.target.matches('button.submit')) {
handleSubmit();
} else if (e.target.matches('button.cancel')) {
handleCancel();
}
});3Best Practices
Follow these guidelines when working with DOM Selection Methods:
1. Use closest() for event delegation patterns
2. Use matches() to test element type in event handlers
3. Scope queries to parent elements to limit DOM traversal
Tip: Use event delegation: attach one listener to a parent, use event.target.closest('.item') to find the clicked item. Much more efficient than attaching listeners to each item.
// Event delegation with closest()
document.querySelector('#list').addEventListener('click', (e) => {
const item = e.target.closest('.list-item');
if (!item) return; // clicked outside any item
console.log('Clicked:', item.dataset.id);
});