Get data attributes for jQuery collection items

This works for the first match:

var attributeValue = $({selector}).data("myAttribute"); 

But if I want to get values ​​for matches of all elements, I do the following:

 var attributes = []; $.each($({selector})), function(k,v) { attributes.push($(v).data("myAttribute")); }); 

It looks stupid. Is there an easier way to get data for all elements?

+4
source share
2 answers

I don’t think there is a built-in way to create an array as you want. But you can simplify the code a bit with $().map() :

 var attributes = $({selector}).map( function( i, element ) { return $(element).data( 'myAttribute' ); }); 

Or, if this is something that can be used in more than one place, you can make it a plugin:

 $.fn.dataArray = function( name ) { return this.map( function( i, element ) { return $(element).data( name ); }); }; 

and name it with this very simple code:

 var attributes = $({selector}).dataArray( 'myAttribute' ); 
+9
source

**** Not an answer! ****

This is for those who want to get data attributes and create markup with these attributes.

Background: I wanted to get data attributes from an element and create html markup on the fly for the number of elements that are in the parent object using these data attributes in the same dynamic markup. This is what I came up with after reading this post. This was for the timeline of events.

 $('.events-content li').map(function() { var date = $(this).data('date'); var year = $(this).data('year'); $('.timeline ol').append('<li><a href="#0" data-date="'+date+'">'+year+'</a></li>'); }); 
0
source

Source: https://habr.com/ru/post/1480854/


All Articles