const list = document.querySelector('ul');
list.addEventListener('click', e => {
const item = e.target.closest('li');
if (!item || !list.contains(item)) return;
// Handle list item click
});
The contains() check verifies that the matched element (found by closest()) is actually a descendant of the delegate container. This is a crucial security measure that prevents handling events from elements outside your container that might match the selector. Without this check, if another matching element elsewhere in the document bubbles through your container, it could trigger your handler unintentionally. This is particularly important in applications with multiple similar components.