How can I get the href of an anchor when I click on it using javascript? I did the following:
function myFunc() {
}
window.onclick = myFunc;
But how to extend the function to respond only to clicks on anchors and get the href?
function linkClick(e) { alert(e.target.href); } links = document.getElementsByTagName('a'); for (i = 0; i < links.length; i++) links[i].addEventListener('click', linkClick, false);
Your document.onclick
registers the handler on the whole document. But you should add it to every link. You can do this with JavaScript and using a framework like Prototype or jQuery makes it a lot easier:
$$('a').invoke('observe', 'click', function(a){
myFunc(a);
});
But you can also use pure JS combining the getElementsByTagName
function with a loop (see Delan's new answer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With