jQuery, get ID of each element in a class using .each?

176,896

Solution 1

Try this, replacing .myClassName with the actual name of the class (but keep the period at the beginning).

$('.myClassName').each(function() {
    alert( this.id );
});

So if the class is "test", you'd do $('.test').each(func....

This is the specific form of .each() that iterates over a jQuery object.

The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t.

Using that form of $.each(), you would need to do it like this:

$.each($('.myClassName'), function() {
    alert( this.id );
});

...which will have the same result as the example above.

Solution 2

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){
  return n.id;
});
alert(arrayOfIds);
Share:
176,896
Rick
Author by

Rick

Web programmer with an interest in web task automation, building websites, etc, I prefer to do everything in Python now as I have moved to it from using a variety of other languages in the past. I also like to do front-end AJAX / javascript work but am moving to do this through Python as well, with the Pyjamas framework.

Updated on November 10, 2021

Comments

  • Rick
    Rick over 2 years

    I'm trying this to get the id of each element in a class but instead it's alerting each name of the class separately, so for class="test" it's alerting: t, e, s, t... Any advice on how to get the each element id that is part of the class is appreciated, as I can't seem to figure this out.. Thanks.

    $.each('test', function() { 
       alert(this)
    });
    
  • user113716
    user113716 almost 14 years
    Indeed $.map() is very nice if an Array is desired. Although if I may express my personal bias, I'd do n.id instead of creating a new jQuery object for each iteration since it's a good deal more efficient. Just thought I'd mention it. :o)
  • jessegavin
    jessegavin almost 14 years
    you're right patrick. no need for the extra $(). I have edited it.