views:

62

answers:

2

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

$.each('test', function() { 
  alert(this)
});
+3  A: 

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.

patrick dw
thank you.. works great now
Rick
@Rick - You're welcome. Glad it works. :o)
patrick dw
A: 

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);
jessegavin
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)
patrick dw
you're right patrick. no need for the extra $(). I have edited it.
jessegavin