How to capture all the anchor element click events with JavaScript?

Sometimes, we want to capture all the anchor element click events with JavaScript.

In this article, we’ll look at how to capture all the anchor element click events with JavaScript.

How to capture all the anchor element click events with JavaScript?

To capture all the anchor element click events with JavaScript, we can use event delegation.

For instance, we write:

<a href='https://example.com/foo'>foo</a>
<a href='https://example.com/bar'>bar</a>

to add 2 anchor elements.

Then we write:

document.addEventListener(`click`, e => {
  if (e.target.tagName.toLowerCase() === 'a') {
    e.preventDefault()
    console.log(`You clicked ${e.target.href}`);
  }
});

to call document.addEventListener to add an event listener to the whole page.

Then we check the tag name of the element is clicked on with e.target.tagName.

If it’s 'a', then we log the href property of it, which has the value of the href attribute of the anchor element.

Conclusion

To capture all the anchor element click events with JavaScript, we can use event delegation.