Event Delegation in JavaScript

Event delegation is a pattern of adding an event listener to a parent node instead, of adding an event listener to the individual node. The added event listener will check for the bubbled event to find matching child element. In this article we will talk about how to implement an event listener using very trending method in JavaScript i.e., event delegation pattern.

Let us consider an example where we have ‘ul’ which contains multiple ‘li’ of animals.

<ul id='animals'>
    <li id='animal1'>Lion</li>
    <li id='animal2'>Tiger</li>
    <li id='animal3'>Jaguar</li>
    <li id='animal4'>Leopard</li>
    <li id='animal5'>Cheetah</li>


Now, here we want to perform an action when we click on the animal (li). As a developer first thing we do is adding an event listener to each ‘li’ and perform whatever action needs to be performed as below.


There is nothing wrong with above method, it will work awesome but but but…. What if list is dynamic, and we need to add or remove some of the animals from the list?

We will do it, and we will also add and remove the list values and their associates event listener. But adding hundreds of event listeners is really a bad idea. This way of adding an event listener will also cause a memory leakage issue and will degrade the performance of your code.

What’s the Solution?

Solution is simple, add an event listener to the parent ‘ul’. But after adding a listener to the ‘ul’ how to find which ‘li’ is clicked?

Again, answer is simple: When event is bubbled up to the ‘ul’ element, you can check the target property of your object and it will help you to get which ‘li’ is clicked from the list. If you want to read more about event bubbling and capturing than do visit my previous article here at:

Please consider below code to achieve what we have talked so far.

document.getElementById("animals").addEventListener("click", function(e) {
  if( && == "LI") {

In above code we are adding event listener to parent element ‘ui’. When the event will be fired we will check the clicked element is ‘LI’ which we can check using ‘’. If it is ‘LI’ we are done.


Most of the developers uses JavaScript library and frameworks like JQuery, AngularJs for their DOM element and event handling. I recommend all of you to use event delegation methods your library or framework is providing. They provide advanced delegation and element identification.

What to read next…

2 Replies to “Event Delegation in JavaScript”

Leave a Reply