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;
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.
id is not a valid jquery function. You need to use the . attr() function to access attributes an element possesses.
//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)
The .get() method will return an array from a jQuery object. In addition you can use .map to project to something before calling get()
var idarray = $("#myDiv")
.find("span") //Find the spans
.map(function() { return this.id; }) //Project Ids
.get(); //ToArray
My suggestion?
var arr = $.map($("#mydiv [id]"), function(n, i) {
return n.id;
});
you could also do this as:
var arr = $.map($("#mydiv span"), function(n, i) {
or
var arr = $.map($("#mydiv span[id]"), function(n, i) {
or even just:
var arr = $("#mydiv [id]").map(function() {
return this.id;
});
Lots of ways basically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With