60

Is there any way that I can get the id of an element from something like:

<a href="#" class="test" id="test_1">Some text</a>
<a href="#" class="test" id="test_2">Some text</a>
<a href="#" class="test" id="test_3">Some text</a>

and then I bind

$('.test')

so when I click one of the elements I get back the id?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Oliver M Grech
  • 3,071
  • 1
  • 21
  • 36

7 Answers7

112

Doh.. If I get you right, it should be as simple as:

$('.test').click(function() {
  console.log(this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="test" id="test_1">Some text</a>
<a href="#" class="test" id="test_2">Some text</a>
<a href="#" class="test" id="test_3">Some text</a>

You can just access the id property over the underlaying dom node, within the event handler.

user2314737
  • 27,088
  • 20
  • 102
  • 114
jAndy
  • 231,737
  • 57
  • 305
  • 359
47

Use "attr" method in jquery.

$('.test').click(function(){
    var id = $(this).attr('id');
});
benck
  • 2,034
  • 1
  • 22
  • 31
  • 1
    The underlying question: Once you've got `this`, you don't really need the `id`, assuming the OP is trying to find the element by its ID, rather than the ID by the element... – Kobi Mar 29 '11 at 10:01
  • 1
    That's right. However, he may want to display the name of id. – benck Mar 29 '11 at 10:21
  • I agree with both, it all depends on your particular task! :) – Oliver M Grech Apr 05 '11 at 21:15
  • `selected.id` would return undefined for me but `selected.attr('id')` worked fine. – dave May 17 '11 at 17:49
8

As of jQuery 1.6, you could (and some would say should) use .prop instead of .attr

$('.test').click(function(){
    alert($(this).prop('id'));
});

It is discussed further in this post: .prop() vs .attr()

Tony L.
  • 17,638
  • 8
  • 69
  • 66
8

When you add a click event, this returns the element that has been clicked. So you can just use this.id;

$(".test").click(function(){
   alert(this.id); 
});

Example: http://jsfiddle.net/jonathon/rfbrp/

Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46
4

Be careful if you use fat arrow functions as you will get undefined for this.id Wasted 10 minutes today wondering what the hell was going on

nasoj1100
  • 528
  • 9
  • 15
3
$(".class").click(function(){
    alert($(this).attr('id'));
});

only on jquery button click we can do this class should be written there

arulmr
  • 8,620
  • 9
  • 54
  • 69
cr7 aj7
  • 101
  • 1
  • 6
0

Nothing from this examples , works for me

for (var i = 0; i < res.results.length; i++) {
        $('#list_tags').append('<li class="dd-item" id="'+ res.results[i].id + '"><div class="dd-handle root-group">' + res.results[i].name + '</div></li>');
}

    $('.dd-item').click(function () {
    console.log($(this).attr('id'));
    });
Niraj
  • 517
  • 1
  • 9
  • 23
nyotsov
  • 93
  • 7