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

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

Live DEMO

Share:
11,883

Related videos on Youtube

Skylar Saveland
Author by

Skylar Saveland

Updated on June 11, 2022

Comments

  • Skylar Saveland
    Skylar Saveland about 2 years

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

  • Skylar Saveland
    Skylar Saveland over 11 years
    why the get() call?
  • gdoron is supporting Monica
    gdoron is supporting Monica over 11 years
    @SkylarSaveland. "As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array." docs
  • Skylar Saveland
    Skylar Saveland over 11 years
    you don't like the potato-programming tag on this question?
  • gdoron is supporting Monica
    gdoron is supporting Monica over 11 years
    @SkylarSaveland, well... since this was the only question in that tag... and nobody uses that phrase... and it's a simple jQuery API question... I think we better without it, but you can return it if you like, it's your question after all.
  • Skylar Saveland
    Skylar Saveland over 11 years
    I just think it's a shame so few use the phrase potato programming :D