I'm trying to implement the following functionality without jQuery:
$(document).on('click', 'a.no-target', function(e) {
e.preventDefault();
});
I have tried with the following piece of code:
document.addEventListener('click', function(e) {
if (e.target.tagName == 'A' && e.target.className.indexOf('no-target') > -1) {
e.preventDefault();
}
});
My problem here is that if I have nested elements like the following ones:
<a href="#" class="more no-target">
<span class="more">Nested element</span>
</a>
the event's target
is the <span>
instead of the <a>
.
Is there a generic solution for this case without having to check the target
's parent?
Note: I need this eventListener to work with dynamically created elements, so I can't attach it directly to the a.no-target
elements.
Thanks.