Javascript event delegation, handling parents of clicked elements?

There is now a method on elements called closest, which does exactly this. It takes a CSS selector as parameter and finds the closest matching ancestor, which can be the element itself. All current versions of desktop browsers support it, but in general it is not ready for production use. The MDN page linked above contains a polyfill.


Here's one way to solve it:

var list = document.getElementsByTagName('ul')[0]

list.addEventListener('click', function(e){
  var el = e.target
  // walk up the tree until we find a LI item
  while (el && el.tagName !== 'LI') {
     el = el.parentNode
  }
  console.log('item clicked', el)
}, false)

This is overly simplified, the loop will continue up the tree even past the UL element. See the implementation in rye/events for a more complete example.

The Element.matches, Node.contains and Node.compareDocumentPosition methods can help you implement this type of features.