Abe Miessler
Abe Miessler

Reputation: 85056

Get data attribute for all matched elements?

Say I have HTML like below:

<div class="test" data-file="1"></div>
<div class="test" data-file="2"></div>

I would like to get a list of all the data-file values. I tried using, $(.test).data("file") but this only returns 1 which makes sense according to jQuery's documentation which states it will return ...the value at the named data store for the first element in the set of matched elements.

Emphasis on first.

Is there any way to tell jQuery to pull all of the data values into an array?

Upvotes: 1

Views: 92

Answers (3)

tymeJV
tymeJV

Reputation: 104785

Of course! Use .map

var dataValues = $(".test[data-file]").map(function() {
    return $(this).data("file");
}).get();

Fiddle: http://jsfiddle.net/5muq33of/

Upvotes: 5

Tushar Gupta
Tushar Gupta

Reputation: 15923

var dataValues = $(".test[data-file]").map(function() {
    return $(this).data("file");
}).get();
console.log(dataValues);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test" data-file="1"></div>
<div class="test" data-file="2"></div>

Upvotes: 0

antyrat
antyrat

Reputation: 27765

You can create temporary array for that purpose:

var myArray = [];
$('.test').each( function() {
    myArray.push( $( this ).data( 'file' ) );
}); 
console.log( myArray );

Upvotes: 2

Related Questions