Emulate jQuery “on” with selector in pure Javascript

Update for 2017: current DOM standards like closest mean this is now much easier.

const addEventForChild = function(parent, eventName, childSelector, cb){      
  parent.addEventListener(eventName, function(event){
    const clickedElement = event.target,
    matchingChild = clickedElement.closest(childSelector)
    if (matchingChild) cb(matchingChild)
  })
};

To use it just:

addEventForChild(parent, 'click', '.child', function(childElement){
  console.log('Woo click!', childElement)
})

Here’s a jsfiddle

Leave a Comment

tech