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

JqueryElementEach

Jquery Problem Overview


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)
});

Jquery Solutions


Solution 1 - Jquery

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 - Jquery

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);

Solution 3 - Jquery

 $(document).ready(function () {
        $('div').each(function () {
            var id = $(this).attr('id');
            console.log(id);
        });
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRickView Question on Stackoverflow
Solution 1 - Jqueryuser113716View Answer on Stackoverflow
Solution 2 - JqueryjessegavinView Answer on Stackoverflow
Solution 3 - JquerySandeep SherpurView Answer on Stackoverflow