tags:

views:

16

answers:

1

I want to get all ids from a collection of items, how can I make this one short line:

var ids = [];
$(".post").each(function(index, element) {
  ids.push($(element).attr("id"));
});

Something like:

var ids = $(".post").map("id");

Thanks.

+3  A: 

Yup! .map() for jQuery objects, or $.map for arrays and objects. The jQuery version will return a jQuery object with the map function applied, so you have to call .get() to get the actual array out of it.

var ids = $(".post").map(function(index, element) { return element.id }).get();
gnarf
+1 for mentioning both map methods
jAndy