Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the list of ids in a particular class using jquery?

e.g.

<div class="myclass" id="div_1"></div>
<div class="myclass" id="div_2"></div>
<div class="notmyclass" id="div_3"></div>

I'd like to end up with array something like ["div_1","div_2"]

like image 727
cjm2671 Avatar asked Sep 20 '11 17:09

cjm2671


2 Answers

After selecting $(".myclass"), you can use the .map() method [docs] to take the .id of each element. This will return a jQuery array-like object containing the ids.

var ids = $(".myclass").map(function() { return this.id; });

Add .toArray() [docs] to the end if you need a real array.

like image 129
Jeremy Avatar answered Oct 13 '22 03:10

Jeremy


var IDs = [];

$('.myclass').each(function(){
    IDs.push( this.id );
});
like image 40
Joseph Silber Avatar answered Oct 13 '22 02:10

Joseph Silber