-2

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>
Basj
  • 41,386
  • 99
  • 383
  • 673

5 Answers5

3

replace e with this, e refers to event object.

alert($(this).attr('id'));

or even better

$('.bleu').click(function(e) {
    alert($(this).attr('id'));
    return false;
})
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

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>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

Use this, and use .prop for id or simply this.id:

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

Alternative if the context is bound on the function, eg while binding events on Backbone views, you can use event.currentTarget, consider this:

$(el).click(function(event) {
  console.log(this) // { "my": "context" }
  console.log(event.currentTarget); // [DOMElement]
}.bind({
  my: 'context'
}));
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0

Use click event and use attr to get id. Try this:

$(".bleu").click(function(e) { 
  alert($(this).attr("id");
});
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
0

User this keyword

 <script>
 test = function(e) {
 debugger;
  alert($(this).attr('id'));
     return false;
    }
    $('.bleu').click(test)

  </script>
Anwar Ul-haq
  • 1,851
  • 1
  • 16
  • 28