I'm trying to convert a jQuery event handler to pure javascript. There are loads of a particular selector on the page, so this was designed with only one event targeting document with that selector:
$(document).on("click", selectorString, function(event) {
// do stuff
});
Where selector
is a list of selectors as a string ".one, .two, .three
".
I'm struggling to replicate this without jQuery though:
document.addEventListener("click", function(event){
if (elementHasClass(event.target, selectorString) {
// do stuff
}
});
But this doesn't have the desired behaviour, as the listener is only on the document
element, rather than the selected element within the document. Can anyone help with this?
It seems like your problem is that it doesn't work on nested elements.
For instance, if you click on a nested span
element that has a parent with the specified class, then it doesn't work because you are merely checking to see if the span
element (which is event.target
) has the class.
To resolve this, you could essentially delegate the event and check to see if any of the event.target
element's parent's elements 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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With