Use event delegation:
document.addEventListener(`click`, e => {
const origin = e.target.closest("a");
if (origin) {
console.clear();
console.log(`You clicked ${origin.href}`);
}
});
<div>
<a href="#l1">some link</a>
<div><a href="#l2"><div><i>some other (nested) link</i></div></a></div>
</div>
[edit 2020/08/20] Modernized
window.onclick = function (e) {
if (e.target.localName == 'a') {
console.log('a tag clicked!');
}
}
The working demo.
Try jQuery and
$('a').click(function(event) { *your code here* });
In this function you can extract href value in this way:
$(this).attr('href')
You can also try using this:
var forEach = Array.prototype.forEach;
var links = document.getElementsByTagName('a');
forEach.call(links, function (link) {
link.onclick = function () {
console.log('Clicked');
}
});
It works, I just tested!
Working Demo: http://jsfiddle.net/CR7Sz/
Somewhere in comments you mentioned you want to get the 'href' value you can do that with this:
var forEach = Array.prototype.forEach;
var links = document.getElementsByTagName('a');
forEach.call(links, function (link) {
link.onclick = function () {
console.log(link.href); //use link.href for the value
}
});
Demo: http://jsfiddle.net/CR7Sz/1/