117. event delegation

JavaScript

medium  - accepted / - tried

What is Event Delegation?

Can you create a function which works like jQuery.on(), that attaches event listeners to selected elements.

In jQuery, selector is used to target the elements, in this problem, it is changed to a predicate function.

onClick(  // root element  document.body,    // predicate  (el) => el.tagName.toLowerCase() === 'div',    function(e) {    console.log(this);    // this logs all the `div` element  })
  1. event.stopPropagation() and event.stopImmediatePropagation() should also be supported.

  2. you should only attach one real event listener to the root element.

Always try to find a better approach.