Sometimes, we want to attach an click event handler to all links with JavaScript.
In this article, we’ll look at how to attach an click event handler to all links with JavaScript.
How to attach an click event handler to all links with JavaScript?
To attach an click event handler to all links with JavaScript, we can use event delegation.
For instance, we write:
<a>foo</a>
<a>bar</a>
<p>
baz
</p>
to add some elements.
Then we write:
window.onclick = (e) => {
if (e.target.tagName !== 'A') {
return
}
console.log('clicked a')
}
to set the window.onclick
property to a click event handler function.
In it, we check if tagName
of the clicked element in the window is 'A'
.
If it’s not, we stop running the function.
Otherwise, we run console.log
.
Therefore, when we clicked an a
element, we see 'clicked a'
logged.
Conclusion
To attach an click event handler to all links with JavaScript, we can use event delegation.