0

What is the (vanilla) javascript equivalent of

$(document).on('click', '#myElement', function() {/*do something*/});

Is there something shorter than

document.addEventListener('click', function(e){
  if (e.target.id=='myElement'){
    /*do something*/
  }
});

I'm wondering if the latter is heavy handed as it will proceed to process all clicks, but the jquery version only proceeds with clicks on the required element, so perhaps there is a more elegant javascript version than this?

I want the handler at document level to deal with subsequently dynamically added elements.

DeeGee
  • 160
  • 6
  • jQuery has to do the exact same thing – Pointy Dec 30 '22 at 21:45
  • No, the jQuery version also processes all clicks. What you're doing now is fine (though it'd be better to use `===`) – CertainPerformance Dec 30 '22 at 21:45
  • jQuery probably uses `.matches()` now, or goes through it's extended selector engine, which you'd want to do for general selectors also. – Pointy Dec 30 '22 at 21:46
  • Here's the [answer to your question](https://stackoverflow.com/a/74863411/383904). `.matches()` is not a good solution for delegation since it misses ancestry. `Event.target.closest()` is the only way to go - since you'd expect a child of a (dynamic) target to be also accounted. Therefore you need to start from a possible `Event.target` child and move up the DOM tree to find the desired "closest" ancestor (or fallback to *self*). – Roko C. Buljan Dec 30 '22 at 22:42

0 Answers0