TrySpace
TrySpace

Reputation: 2460

Find and list every element's id value

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

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

var listy = '';

$("div span").each(function(){  
  listy += this.id ;  
});

jsBin demo


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. 

jsBIn demo 2

Upvotes: 1

gdoron
gdoron

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();

Live DEMO

If you want only <span> with id attribute defined, change the selector to:

$(div span[id]).map(...)

If you want all the ids 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

ioseb
ioseb

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

Related Questions