Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 634
TrySpace Avatar asked Jun 10 '26 06:06

TrySpace


2 Answers

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

like image 53
gdoron is supporting Monica Avatar answered Jun 11 '26 19:06

gdoron is supporting Monica


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.

like image 27
ioseb Avatar answered Jun 11 '26 19:06

ioseb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!