The usual equivalent of javascript $ (document) .on (event) with a selector

I am trying to convert a jQuery event handler to pure javascript. There are many specific selectors on the page, so this was developed using just one document targeting events with this selector:

$(document).on("click", selectorString, function(event) { // do stuff }); 

Where selector is a list of selectors as the string " .one, .two, .three ".

I am trying to replicate this without jQuery though:

 document.addEventListener("click", function(event){ if (elementHasClass(event.target, selectorString) { // do stuff } }); 

But this does not have the desired behavior, because the listener is only in the document element, and not in the selected element inside the document. Can anyone help with this?

+5
source share
1 answer

Your problem seems to be that it does not work on nested elements.

For example, if you click on a nested span element that has a parent with the specified class, then it does not work, because you just check if the span element (which event.target ) has a class.

To solve this problem, you can delegate the event and check if any of the parent elements of the event.target element have the specified class:

Example here

 document.addEventListener("click", function (e) { var target = e.target; while (target && target.parentNode !== document) { target = target.parentNode; if (!target) { return; } // If element doesn't exist if (target.classList.contains('target')){ // do stuff console.log(e.target); } } }); 
+1
source

Source: https://habr.com/ru/post/1236446/


All Articles