开发者

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

开发者 https://www.devze.com 2023-04-06 18:15 出处:网络
e.g. <div class=\"myclass\" id=\"div_1\"></开发者_StackOverflow社区div> <div class=\"myclass\" id=\"div_2\"></div>

e.g.

<div class="myclass" id="div_1"></开发者_StackOverflow社区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"]


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.


var IDs = [];

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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消