Javascript attach an onclick event to all links
getElementsByTagName is supported by all modern browsers and all the way back to IE 6
var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
// stuff
}
}
I wanted to offer an improvement on @zatatatata's answer which also works with links with nested elements.
function findLink(el) {
if (el.tagName == 'A' && el.href) {
return el.href;
} else if (el.parentElement) {
return findLink(el.parentElement);
} else {
return null;
}
};
function callback(e) {
const link = findLink(e.target);
if (link == null) { return; }
e.preventDefault();
// Do something here
};
document.addEventListener('click', callback, false);
If the clicked element isn't a link, we search its parents to check for a link element.
function linkClickHandler(a) {
console.log(a.host);
}
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) links[i].onclick = function() {
linkClickHandler(links[i]);
}
It's weird that nobody offered an alternative solution that uses event bubbling
function callback(e) {
var e = window.e || e;
if (e.target.tagName !== 'A')
return;
// Do something
}
if (document.addEventListener)
document.addEventListener('click', callback, false);
else
document.attachEvent('onclick', callback);
The pros of this solution is that when you dynamically add another anchor, you don't need to specifically bind an event to it, so all links will always fire this, even if they were added after these lines were executed. This is in contrast to all the other solutions posted so far. This solution is also more optimal when you have a large number of links on your page.