JavaScript Event Delegation Working

Introduction

 
Event delegation is one of the very good methodologies present in the JavaScript platform. Event Delegation provides an option to programmers to avoid adding an event listener to every specific node. By the use of JavaScript Event Delegation the event listener is to be added to only one parent. And that parent analyzes events to find a match on a child element.
 
Example
 
Suppose we have a parent OL element with some child elements:
  1. <ol id="parent-list">  
  2.             <li id="p1">ItemNumber 1</li>  
  3.             <li id="p2">ItemNumber 2</li>  
  4.             <li id="p3">ItemNumber 3</li>  
  5.             <li id="p4">ItemNumber 4</li>  
  6.             <li id="p5">ItemNumber 5</li>  
  7.             <li id="p6">ItemNumber 6</li>  
  8. </ol> 
May be sometime a task need to happen where each child is clicked. The programmer can add a separate event listener to each individual LI element, and also if LI elements are frequently added and removed from the ordered list, then frequently adding and removing  event listener will be tough work. The programming solution for this will be to add an event listener to the parent and when the event bubbles up to the OL element, programmer check the event object's target property to get the reference of the actual clicked node.
 
JavaScript snippet to explain Event Delegation
  1. document.getElementById ("parent-list").addEventListener("click",function(ev) {  
  2.             // ev.target is the clicked element!  
  3.             // If it was a list item  
  4.             if(ev.target && ev.target.nodeName == "LI") {  
  5.                         // List item found!  Output the ID!  
  6.                         console.log("List item ",e.target.id.replace("post-")," was clicked!");  
  7.             }  
  8. });