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 <span>.click-me</span> class.

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

<span class="nx">$</span><span class="p">(</span><span class="s1">'.click-me'</span><span class="p">).</span><span class="nx">click</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
	<span class="c1">// Do things...
</span><span class="p">});</span>

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.