Skip to content Skip to sidebar Skip to footer

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 resp

Solution 1:

function linkClick(e) {
  alert(e.target.href);
}
links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++)
  links[i].addEventListener('click', linkClick, false);

Solution 2:

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

Solution 3:

it won't work like this, you need to setup an onclick handler for every anchor. The easiest way to do this, is to use a javascript framework like jQuery or Prototype or something similar.

extend your function to recieve the calling object:

var myFunc = function(target) {
  var href = target.href;
  // ... your function code that can now see the href of the calling anchor
}

jQuery:

$('a').click(function(){
  myFunc(this);
});

Protype: see Kau-Boy's answer

Solution 4:

functionmyFunc(link) {
  alert(link.href);
  returnfalse; // return false if you don't want to actually navigate to that link
}


<a href onclick="return myFunc(link)">something</a>

Post a Comment for "Javascript Get Anchor Href On Click"