Using jQuery to get data attribute values with .each()
Asked Answered
S

3

19

I have the following HTML with data attributes - I want to write some jQuery that will loop through the HTML and collect the data attributes and put them into an array - could anyone assist as I'm getting an error.

I am trying to use the data() attribute - can you see what I'm doing wrong?

<span class="winners" data-userid="123" data-position="1" data-fullname="neil">
<span class="winners" data-userid="234" data-position="2" data-fullname="Ron">
<span class="winners" data-userid="421" data-position="3" data-fullname="Philip">
var multi = $('.winners');
var winners_array = [];

$.each(multi, function (index, item) {
    winners_array.push( {name: 'fullname', value: item.data('fullname')} );  
});

console.log(winners_array);

Console error:

item.data is not a function

Stevie answered 23/1, 2014 at 11:41 Comment(0)
E
39

item is not a jQuery object, the arguments for each are the index and the native DOM element

var multi = $('.winners');
var winners_array = [];

$.each(multi, function (index, item) {
    winners_array.push( {name: 'fullname', value: $(item).data('fullname')} );  
});

using a map would be easier

var winners_array = $.map($('.winners'), function(el) {
     return {name: 'fullname', value: $(el).data('fullname')}
});
Encyclical answered 23/1, 2014 at 11:43 Comment(0)
A
6

I understand you should use $(item), instead data only. Kindly find the code below:

<script type="text/javascript">
        var multi = $('.winners');
        var winners_array = [];

        $.each(multi, function (index, item) {
            winners_array.push( {name: 'fullname', value: $(item).data('fullname')} );  
        });

        console.log(winners_array);
    </script>
Arminius answered 23/1, 2014 at 11:54 Comment(0)
I
3

Use item.dataset.fullname instead.

var multi = $('.winners');
var winners_array = [];

$.each(multi, function (index, item) {
    winners_array.push( {name: 'fullname', value: item.dataset.fullname} );  
});

console.log(winners_array);
Idiocy answered 23/1, 2014 at 11:45 Comment(2)
This is only supported in IE11, and generally isn't supported in older browsers at all. You'd be better of using getAttribute('data-fullname'). Also note that jQuery's data() stores data internally, so if the value is set or changed with data() this won't work either.Encyclical
Are you sure? I just verified it in the Chrome console.Idiocy

© 2022 - 2024 — McMap. All rights reserved.