Reputation: 2460
I'm trying to get all the found elements within a <div>
, but by default it stops when it found the first occurrence, but I want it to list every found element's id
value.
So this doesn't work:
listy = $("DIV").find("SPAN").attr("id");
I've been experimenting with .get
and .map
, but I think they're not what I want..
Upvotes: 2
Views: 245
Reputation: 206669
var listy = '';
$("div span").each(function(){
listy += this.id ;
});
Or like:
var listy = []; // create array
$("div span[id]").each(function(){ // span with ID data
listy.push( this.id ); // push ID names into array
});
// Now use listy.join(); to see the list
// you can also do: listy+'' to transform it into string.
Upvotes: 1
Reputation: 150313
listy = $("div").find("span").map(function(){
return this.id;
}).get();
Without find
is even better:
listy = $("div span").map(function(){
return this.id;
}).get();
If you want only <span>
with id
attribute defined, change the selector to:
$(div span[id]).map(...)
If you want all the id
s as a string:
listy = $("div span").map(function(){
return this.id;
}).get().join('');
The parameter of join
is the delimiter, e.g. .join('-')
or .join(',')
or without: .join('')
Upvotes: 12
Reputation: 16949
Maybe this way?
var ids = [];
$("div span").each(function() {
if (this.id) {
ids.push(this.id);
}
});
attr() method will always return first elements attribute only.
Upvotes: 1