Retrieve data attribute values for jQuery collection's elements -
this works first match:
var attributevalue = $({selector}).data("myattribute");
but if want values elements selector matches, following:
var attributes = []; $.each($({selector})), function(k,v) { attributes.push($(v).data("myattribute")); });
this feels stupid. there simpler way data elements?
i don't think there built-in way make array want. can simplify code tiny bit $().map()
:
var attributes = $({selector}).map( function( i, element ) { return $(element).data( 'myattribute' ); });
or if might used in more 1 place, make plugin:
$.fn.dataarray = function( name ) { return this.map( function( i, element ) { return $(element).data( name ); }); };
and call simple code:
var attributes = $({selector}).dataarray( 'myattribute' );
Comments
Post a Comment