简体   繁体   中英

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?

Of course! Use .map

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

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

You can create temporary array for that purpose:

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

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM