This works for the first match:
var attributeValue = $({selector}).data("myAttribute");
But if I want to get values for all elements selector matches, I do the following:
var attributes = [];
$.each($({selector})), function(k,v) { attributes.push($(v).data("myAttribute")); });
This feels stupid. Is there simpler way to get the data for all the elements?
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to "5" .
To get all DOM elements by a data attribute, use the querySelectorAll method, e.g. document. querySelectorAll('[data-id]') . The querySelectorAll method returns a NodeList containing the elements that match the specified selector.
We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.
I don't think there is a built-in way to make an array like you want. But you can certainly simplify the code a tiny bit with $().map()
:
var attributes = $({selector}).map( function( i, element ) {
return $(element).data( 'myAttribute' );
});
Or if this is something that might be used in more than one place, you could make it 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' );
Inspired by Michael Geary's answer above, I have come up with a similar solution.
This is for anyone that wants to retrieve data attributes and create markup with those attributes.
Background: I wanted to retrieve data attributes from an element and create html markup on the fly for as many elements that are in the parent, using those data attributes in the same dynamic markup. This is what I came up with after reading this post. This was for an event timeline.
$({selector}).map(function() {
var foo = $(this).data('foo');
var bar = $(this).data('bar');
$({anotherSelector}).append('<li><a href="#0" data-foo="'+foo+'">'+bar+'</a></li>');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With