jquery: get id from class selector

JavascriptJqueryHtml

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Use "attr" method in jquery.

$('.test').click(function(){
    var id = $(this).attr('id');
});

Solution 3 - Javascript

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/

Solution 4 - Javascript

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: https://stackoverflow.com/questions/5874652/prop-vs-attr

Solution 5 - Javascript

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

Solution 6 - Javascript

$(".class").click(function(){
    alert($(this).attr('id'));
});

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

Solution 7 - Javascript

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'));
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOliver M GrechView Question on Stackoverflow
Solution 1 - JavascriptjAndyView Answer on Stackoverflow
Solution 2 - JavascriptbenckView Answer on Stackoverflow
Solution 3 - JavascriptJonathon BolsterView Answer on Stackoverflow
Solution 4 - JavascriptTony L.View Answer on Stackoverflow
Solution 5 - Javascriptnasoj1100View Answer on Stackoverflow
Solution 6 - Javascriptcr7 aj7View Answer on Stackoverflow
Solution 7 - JavascriptnyotsovView Answer on Stackoverflow