-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
  • 36,818
  • 81
  • 313
  • 561

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
  • 64,240
  • 8
  • 67
  • 88
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
  • 110,383
  • 23
  • 155
  • 178
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
  • 44,338
  • 13
  • 91
  • 116
0

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

$(".bleu").click(function(e) { 
  alert($(this).attr("id");
});
Dhara Parmar
  • 7,791
  • 1
  • 14
  • 25
0

User this keyword

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

  </script>
Anwar Ul-Haq
  • 1,786
  • 1
  • 13
  • 26