90

Does anyone know how can I get the clicked link's href with jquery? I have the link as following:

    <a  href="ID=1" class="testClick">Test1.</a>
    <br />
    <a  href="ID=2" class="testClick">Test2.</a>
    <br />
    <a  href="ID=3" class="testClick">Test3.</a>

I wrote a code as following to get the href value from the link I clicked on. But somehow this is always return me the 1st link's href (ID=1) even though I clicked on Test2 or Test3. Does anyone know what is it going on here? and how can I solve this issue?

    $(".testClick").click(function () {
        var value = $(".testClick").attr("href");
        alert(value );
    });
Jin Yong
  • 42,698
  • 72
  • 141
  • 187

4 Answers4

183

this in your callback function refers to the clicked element.

   $(".addressClick").click(function () {
        var addressValue = $(this).attr("href");
        alert(addressValue );
    });
Daff
  • 43,734
  • 9
  • 106
  • 120
  • 18
    Or one can just access it directly instead of creating a jQuery object. `var addressValue = this.href;` – Chris Apr 01 '11 at 00:43
  • 1
    FYI, if the href is relative `href="sibling_file.htm"` then $(this).attr("href") returns `sibling_file.htm` and this.href returns `https://example.com/folder/sibling_file.htm` (which is what I'd expected and wanted.) – Redzarf Dec 16 '17 at 22:34
19

You're looking for $(this).attr("href");

Matt
  • 43,482
  • 6
  • 101
  • 102
13
$(".testClick").click(function () {
         var value = $(this).attr("href");
         alert(value );     
}); 

When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.

Paul
  • 544
  • 4
  • 12
6

Suppose we have three anchor tags like ,

<a  href="ID=1" class="testClick">Test1.</a>
<br />
<a  href="ID=2" class="testClick">Test2.</a>
<br />
<a  href="ID=3" class="testClick">Test3.</a>

now in script

$(".testClick").click(function () {
        var anchorValue= $(this).attr("href");
        alert(anchorValue);
});

use this keyword instead of className (testClick)

vishal ribdiya
  • 1,013
  • 2
  • 12
  • 20