Getting the identifier of all elements of a certain class in an array

Here is what I am trying to do:

I am currently using this to create an array of all elements matching the name of the .cookie class. Right now I am getting the text value of this element, and this is not what I need:

 var getAllCookies = $('.cookie').text(); var cookiesArray = jQuery.makeArray(getAllCookies); alert(cookiesArray[0]); 

I need to find all the elements of a particular class (.cookie), get this element id value and store this ID value inside the array.

+7
source share
3 answers

I think this should do what you need:

 var ids = $('.cookie').map(function(index) { // this callback function will be called once for each matching element return this.id; }); 

Documentation for map .

Here's a working jsFiddle demo .

+16
source

You can try:

 var cookiesArray = []; $('.cookie').each( function(i,e) { /* you can use e.id instead of $(e).attr('id') */ cookiesArray.push($(e).attr('id')); }); 
+3
source
 var cookiesArray = new Array(); $('.cookie').each(function() { var id = $(this).attr(id); if(id != undefined) { cookiesArray.push(id); } }); 
+1
source

All Articles