Sorry for another duplicate.
I'm trying to bind a click event listener to links which will be dynamically created later. Unfortunately this doesn't work:
document.querySelector('body').addEventListener('click', function(e) {
if (e.target.tagName.toLowerCase() === 'a') {
e.preventDefault();
console.log("click")
}
});
Strangely it also doesn't work on a link which is not created dynamically. It is however working on the body, but that's not the target.
I also tried if (e.target.classList.contains("someclass")) {}
The DOM nodes are body->header->div->a if that makes a difference. (?)
Thanks for any advice on how to make it work!
console.log('foo')to the handler on the parent element, and click the (child) link, does it fire? If not, there's a problem with your understanding of event delegation (and we'll likely need to see your DOM/HTML more). If it is, there's a problem with your logic ... but the two are very different problems.