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