jQuery, get ID of each element in a class using .each?
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);
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, 2021Comments
-
Rick over 2 years
I'm trying this to get the
id
of each element in aclass
but instead it's alerting each name of the class separately, so forclass="test"
it's alerting:t
,e
,s
,t
... Any advice on how to get the each elementid
that is part of theclass
is appreciated, as I can't seem to figure this out.. Thanks.$.each('test', function() { alert(this) });
-
user113716 almost 14 yearsIndeed
$.map()
is very nice if an Array is desired. Although if I may express my personal bias, I'd don.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 almost 14 yearsyou're right patrick. no need for the extra $(). I have edited it.