Jquery - How list id elements contained from a div
If I have a div like this:
<div id="box">
<开发者_StackOverflow;div class="but" id="1">Text 1</div>
<div class="but" id="2">Text 2</div>
</div>
How can I create an array of all IDs of the .but
elements contained in the #box
div?
In the example will be [1, 2]
.
var ids = $('#box > .but').map(function() {
return this.id || null;
}).get();
This will create an entry for every .but
child of the #box
element iff it has an ID (null
values are discarded, if an element has no ID, this.id
will return an empty string (which evaluates to false
)). If every element has definitely an ID or you don't care/want potentially empty values in the array, you can omit the || null
part.
If you want to get the ID of every .but
descendant, change the selector to:
$('#box .but')
Reference: .map()
, .get()
This should work:
var idArray = new Array();
$('#box .but').each(function() {
idArray.push(this.id);
});
JSFiddle Example
You can use .each to loop through all elements in a result set:
var ar=[]
$('div.but').each(function(){
ar.push(this.id);
});
Here's a working fiddle.
How about this:
var ar = jQuery('div#box').children('.but').map( function() {
return jQuery(this).attr('id');
}).get();
alert(ar);
@flexi kling thanks for the information of beautiful functions map
and get
DEMO
Try something like
var idArray = new Array();
$(".but").each(function(index, item) { idArray.push(item.id); });
精彩评论