Consider this example:
You're creating a website that uses client-side rendering.
When the user clicks a link, you want to disable the browser's navigation and render the new page yourself.
Perhaps you also have some html like this, and you want to call upvote_post(id) every time the button is clicked:
<post-element data-id=12345>
...
<upvote-button></upvote-button>
</post-element>
The common way to handle both of these cases would be to add a click event handler on every <a>, <upvote-button>, etc. element that you generate.
But wouldn't it be better to just add an event handler on the document itself?
document.addEventListener('click', function(e) {
for (let elem of e.path) {
if (elem instanceof HTMLAnchorElement && elem.origin==window.location.origin) {
e.preventDefault()
render_page(elem.href)
break
} else if (elem.tagName=='UPVOTE-BUTTON') {
let post = elem.closest('post-element')
upvote_post(post.dataset.id)
break
}
}
})
Of course, it feels wrong to bypass the builtin event handler system, but I can't think of any disadvantages here.
You can still add event handlers to specific elements if you need to, but for common actions, this seems like a better solution.