var attributeValue = $({selector}).data("myAttribute ");
But if I want to get the matching values of all element selectors, I will do the following:
var attributes = [];< br />$.each($({selector})), function(k,v) {attributes.push($(v).data("myAttribute")); });
This It feels silly. Is there an easier way to get the data of all elements?
var attributes = $({selector}).map( function( i, element) {
return $(element).data('myAttribute' );
});
Or, if this may be used in multiple places, you can set it as a plugin:
$.fn.dataArray = function( name) {
return this.map( function( i, element) {
return $(element).data( name );
});
};
and call it with this very simple code:
var attributes = $({selector}).dataArray('myAttribute' );
This applies to the first game:
var attributeValue = $({selector}).data("myAttribute");
But if I want to get the matching value of all element selectors, I will do the following:
var attributes = [];
$.each($({selector})), function(k,v) {attributes.push($(v).data ("myAttribute")); });
This feels silly. Is there an easier way to get the data of all elements?
I don’t think there is a built-in method to make the array you want. But you can use $().map() to simplify the code. < p>
var attributes = $({selector}).map( function( i, element) {
return $(element).data('myAttribute' );
});
Or, if this may be used in multiple places, you can set it as a plug-in:
$ .fn.dataArray = function( name) {
return this.map( function( i, element) {
return $(element).data( name );
});
};
And use this very simple code to call it:
var attributes = $({selector}).dataArray('myAttribute' );