cjm2671
cjm2671

Reputation: 19496

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"]

Upvotes: 6

Views: 3297

Answers (3)

culebr&#243;n
culebr&#243;n

Reputation: 36563

Besides .map you need .get() if you want an array in the end:

$('.myclass').map(function() { return this.id; }).get();

Upvotes: 1

Jeremy Banks
Jeremy Banks

Reputation: 129756

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.

Upvotes: 13

Joseph Silber
Joseph Silber

Reputation: 220146

var IDs = [];

$('.myclass').each(function(){
    IDs.push( this.id );
});

Upvotes: 1

Related Questions