JQuery, get the id of each element in a class using .each?

I try to get the id each element in class , but instead it warns each class name separately, so for class="test" it warns: t , e , s , t ... Any advice on how to get each id element is welcome , which is part of the class , as I cannot understand this. Thank.

 $.each('test', function() { alert(this) }); 
+50
jquery each element
Aug 15 '10 at 1:24
source share
2 answers

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

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

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

This is a concrete view of .each() that .each() over a jQuery object.

The form you used is iterating over any type of collection. So you essentially repeated the array of characters t,e,s,t .

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

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

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

+118
Aug 15 '10 at 1:26
source share
Answer to

patrick dw is right.

For kicks and giggles, I thought I'd post a simple way to return an array of all identifiers.

 var arrayOfIds = $.map($(".myClassName"), function(n, i){ return n.id; }); alert(arrayOfIds); 
+22
Aug 15 '10 at 1:36
source share



All Articles