Basj Basj - 7 months ago 10
Javascript Question

Get the id of the clicked link

I'd like to get the id of the clicked link with jQuery. Why does this return

Undefined
instead?



test = function(e) {
alert($(e).attr('id'));
return false;
}
$('.bleu').click(test)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="" class="bleu" id="h12">azeaze12</a>
<a href="" class="bleu" id="h13">azeaze13</a>
<a href="" class="bleu" id="h14">azeaze14</a>




Answer

You need to use this it refers to the clicked dom element, first parameter in click event handler is event object

test = function(e) {
    alert($(this).attr('id'));
    return false;
}
$('.bleu').click(test)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="" class="bleu" id="h12">azeaze12</a>
<a href="" class="bleu" id="h13">azeaze13</a>
<a href="" class="bleu" id="h14">azeaze14</a>