What is event delegation

Event delegation refers to delegating what you want to do to your ancestor and then implementing your own events using the bubbling mechanism.

In summary, event delegate is when a child element fires an event, and listeners are placed above the parent or ancestor element. Based on this mechanism, we can add listeners on all related ancestor elements

<div id="div1"> <button>123</button> </div> div1.addEventListener("click",(e)=>{ const t = e.target If (t.tagname.tolowCase () === 'button'){console.log(" Button was clicked ")}})Copy the code

This code does not bind events to the button, but it still prints that the button was clicked. This is the event delegate

Two advantages of event delegation

  • // If 100 child elements trigger the same listener, it can be placed on top of the parent element.

  • // Create an element with createElement and place listeners on top of the parent element.