Is it possible to get an array consisting of all id's on a page with jQuery?
+6
A:
You could do this:
var ids = new Array();
$('[id]').each(function() { //Get elements that have an id=
ids.push($(this).attr("id")); //add id to array
});
//do something with ids array
One note I saw testing this, the FireBug console counts as one, if that's enabled just be aware.
Nick Craver
2010-03-02 22:21:41
Re: Firebug - `$('body [id]')` might be a better option, then, if one can be certain that we don't want `head` elements or the like.
Matchu
2010-03-02 22:26:03
+2
A:
I think this would work
var array = [];
$("*").each(function(){
if(this.id) array.push(this.id);
});
BenMills
2010-03-02 22:23:10
+6
A:
var ids = $('*[id]').map(function() {
return this.id;
}).get();
The .map() method is particularly useful for getting or setting the value of a collection of elements.
karim79
2010-03-02 22:24:30
This is the sort of thing where to some it's much cleaner, and to those who can't wrap their head around it much uglier.
Matchu
2010-03-02 22:27:03