JavaScript optimization - Event delegation

Dealing with events in JavaScript is easy when you are working with jQuery or other language. Adding .on() or addEventListener() to next object is one of the ways but when you have group of objects to which you are still adding new objects you have to repeat adding events to each new element. With Event delegation you can omit this problem.

HTML of Event Delegation:

<a id="add-button">Add</a>
<ul id="parent">

JavaScript code of Event Delegation:

document.getElementById("parent").addEventListener("click",function(e) {
    if( && == "li") { = parseInt(;

document.getElementById("add-button").addEventListener("click", function(e) {  
  var para = document.createElement("li");
  var node = document.createTextNode("0");


CODEPEN of Event Delegation:

See the Pen FwftB by (@fedojo_com) on CodePen.

As you can see in preview each element in <ul id=”parent”> has click listener. Element <a id=”add-button”> is adding new element which has event listener added. You dont have to repeat addEventListener() to each element so when you have more events added on element (for example mouseenter, mouseleave etc) they are added automaticaly.

How to Event Delegation in jQuery:


$( "#parent" ).on( "click", "li", function( event ) {
    // here your code