Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get anchor href on click

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?

like image 581
Infinite Possibilities Avatar asked Dec 07 '22 02:12

Infinite Possibilities


2 Answers

function linkClick(e) {
  alert(e.target.href);
}
links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++)
  links[i].addEventListener('click', linkClick, false);
like image 82
Delan Azabani Avatar answered Dec 21 '22 17:12

Delan Azabani


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).

like image 21
2ndkauboy Avatar answered Dec 21 '22 18:12

2ndkauboy