0

There is feature click binding on selector

$(document).on("click", ".onClass", function () {
    //your code
    var element = $(this); // to get clicked element
});

Is there any analog with pure js?

P.S. I have seen this solution How to get the element clicked (for the whole document)? but it is not a solution i am expecting.

Andrii
  • 324
  • 3
  • 16

1 Answers1

0

You can bind the event listener to the document in the same way, but you need to test the target element to see if either it or one of its ancestors, matches the selector.

document.addEventListener('click', (event) => {
    const selector = ".onClass";
    const element = event.target;
    if (!element.closest(selector)) return; // No match so abort here
    // Otherwise: Do stuff with element
});
connexo
  • 53,704
  • 14
  • 91
  • 128
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • https://stackoverflow.com/questions/23508221/vanilla-javascript-event-delegation#answer-23978597 – Andrii Feb 21 '22 at 09:55