Retrieve data attribute values for jQuery collection's elements
Asked Answered
D

2

6

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?

Demolish answered 15/5, 2013 at 5:55 Comment(0)
M
13

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' );
Mutz answered 15/5, 2013 at 6:19 Comment(1)
One thing to notice here is that jQuery's .map() function returns a jQuery object but sometimes you could just need the underlying array. For that just add .get() at the end of .map(...)Cliquish
T
1

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>');
});
Tor answered 9/2, 2017 at 1:7 Comment(2)
While it was not an answer per se, I do feel it is relevant to the original question and thus as you have indicated, I have changed my answer somewhat to be hopefully a useful answer.Tor
The syntax benefit in this answer is that no parameters are written in the anonymous function and $(this) is used within.Merrymaker

© 2022 - 2024 — McMap. All rights reserved.