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

3

67

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)
});
Dariodariole answered 15/8, 2010 at 1:24 Comment(0)
W
156

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.

Whimsicality answered 15/8, 2010 at 1:26 Comment(1)
thanks, your answer is instructive!Extraneous
G
30

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);
Gaily answered 15/8, 2010 at 1:36 Comment(2)
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)Whimsicality
you're right patrick. no need for the extra $(). I have edited it.Gaily
S
1
 $(document).ready(function () {
        $('div').each(function () {
            var id = $(this).attr('id');
            console.log(id);
        });
    });
Sphenogram answered 9/11, 2021 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.