117. event delegation

JavaScript
Is this helpful ?

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.

Let's try to solve this problem within 10 mintues.

Discuss(14)