You don't need to attach listeners to every anchor element.
Using event delegation you can attach a single event listener to the footer element, and in the callback function check whether or not the clicked element was an anchor — then execute code related to each specific case.
Element.matches()
can be used to check if the element that was clicked was an anchor, and then Event.preventDefault()
can be used to prevent the default navigation behavior for the clicked anchor.
Here's a complete example:
const footer = document.querySelector('footer');
function handleFooterClick (ev) {
console.clear();
// The click event was dispatched from an anchor element:
if (ev.target.matches('a')) {
// Prevent the default anchor navigation:
ev.preventDefault();
console.log('You would have navigated to:', ev.target.href);
}
else { // Not an anchor:
console.log('You clicked another element:', ev.target.tagName);
}
}
footer.addEventListener('click', handleFooterClick);
<footer>
<h2>heading</h2>
<div>
<a href='a.aspx'>test 1</a>
<a href='b.aspx'>test 2</a>
</div>
<a href='c.aspx'>test 3</a>
</footer>