Get list of data-foo attributes for set of jQuery elements

Skylar Saveland picture Skylar Saveland · Mar 2, 2013 · Viewed 11k times · Source

I can use attr to "Get the value of an attribute for the first element in the set of matched elements ..."

To get the list of attributes, do I need to build it up manually with $(..).each or is there a convenience?

$('tr.food-row')
[
<tr class=​"food-row" data-pk=​"11457">​…​</tr>​
, 
<tr class=​"food-row" data-pk=​"11429">​…​</tr>​
]
$('tr.food-row').attr('data-pk')
"11457"

I want to get ["11457", "11429"].

Answer

var allAttributes = $('tr.food-row').map(function(){
    return $(this).data('pk');
}).get();

Live DEMO