Monday, May 6, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  9] [ 7]  / answers: 1 / hits: 132668  / 15 Years ago, tue, may 5, 2009, 12:00:00

I am trying to gather a list (array) of ids in a sector



<div id=mydiv>
<span id='span1'>
<span id='span2'>
</div>

$(#mydiv).find(span);


gives me a jQuery object, but not a real array;



I can do



var array = jQuery.makeArray($(#mydiv).find(span));


and then use a for loop to put the id attributes into another array



or I can do



$(#mydiv).find(span).each(function(){}); //but i cannot really get the id and assign it to an array that is not with in the scope?(or can I)


Anyhow, I just wanna see if there is a shorthand in jQuery to do that;


More From » jquery

 Answers
98

//but i cannot really get the id and assign it to an array that is not with in the scope?(or can I)




Yes, you can!



var IDs = [];
$(#mydiv).find(span).each(function(){ IDs.push(this.id); });


This is the beauty of closures.



Note that while you were on the right track, sighohwell and cletus both point out more reliable and concise ways of accomplishing this, taking advantage of attribute filters (to limit matched elements to those with IDs) and jQuery's built-in map() function:



var IDs = $(#mydiv span[id])         // find spans with ID attribute
.map(function() { return this.id; }) // convert to set of IDs
.get(); // convert to instance of Array (optional)

[#99590] Friday, May 1, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darennevina

Total Points: 422
Total Questions: 128
Total Answers: 105

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;