DEV Community


Posted on

How JavaScript Event Delegation Works

Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent.

For Example - Let's say that we have a parent UL element with several child elements:

<ul id="parent-list">
    <li id="post-1">Item 1</li>
    <li id="post-2">Item 2</li>
    <li id="post-3">Item 3</li>
    <li id="post-4">Item 4</li>
    <li id="post-5">Item 5</li>
    <li id="post-6">Item 6</li>

Now something needs to be done when li element is clicked one way is to attach event listener to all the li elements but what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare, especially if addition and removal code is in different places within your app.

The better solution is to add an event listener to the parent UL element. But if you add the event listener to the parent, how will you know which element was clicked?

Simple: when the event bubbles up to the UL element, you check the event object's target property to gain a reference to the actual clicked node.

Javascript snippet

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {
    // is the clicked element!
    // If it was a list item
    if( && == "LI") {
        // List item found!  Output the ID!
        console.log("List item ","post-", ""), " was clicked!");

Hopefully this helps you visually the concept behind event delegation and convinces you of delegation's power!

Top comments (0)