Why event delegation is a better way to listen for events in vanilla JS

Let’s say you wanted to listen for clicks on an element with the .click-me class.

With jQuery, whether there’s one element or 100, you do this.

$('.click-me').click(function (event) {
	// Do things...

Web performance #

It feels like listening to every click in the document would be bad for performance, but it’s actually more performant than having a bunch of event listeners on individual items.

.. With a traditional approach, attaching listeners to specific elements, you would need to add a new listener every time you added a field. With event delegation, you can setup your listener once and not have to worry about it, since it checks selectors at time of click rather than when the DOM is initially rendered.