3

I need to push all my ID's into an array, both ways I've tried this only pushes the first ID into the array:

  var some = [];
  $('ul#jdLists li').each(function () {
   some.push([$('ul#jdLists li').attr("id")]);
  });

This returns the correct number of items in the array but with the ID of the first li

or

    var some = [];                
    some.push([$('ul#jdLists li').attr("id")]);

this returns a single item with the first li ID

thanks

1
  • .attr and other getter methods get the value from the first selected element because there's no way of knowing which element you want to get the attribute from. Commented Dec 21, 2012 at 16:30

3 Answers 3

11

This piece of code: some.push([$('ul#jdLists li').attr("id")]); will push id of first li found by ul#jdLists li selector, what you need to do is to get id of each li, which can be done inside each function:

var some = [];
$('ul#jdLists li').each(function () {
   some.push($(this).attr("id"));
   // or
   some.push(this.id);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Using some.push(this.id) would save creating a new jQuery object for every element.
Yeah, I've edited my answer to include it, thanks for comment.
that worked like a charm, thanks I was close but yet still far off
4

or you can use $.map():

var ids = $('ul#jdLists li').map(function () {
   return this.id;
}).get();

1 Comment

A much more elegant solution IMO
0
var some = [];
$('ul#jdLists li').each(function (i, el) {
   some.push(el.id);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.