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

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.

ERROR in console log : item.data is not a function

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

  • how to use for each with mustache javascript?
  • Nested Each Loop Causing Problem
  • return false or return true doesn't skip to next loop in jQuery
  • jQuery variable scope within each
  • The difference between assigning event handlers with bind() and each() in jQuery?
  • .each not working to separate sections
  • // My HTML code

    <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">
    

    // My jQuery code

    var multi = $('.winners');
    var winners_array = [];
    
    $.each(multi, function (index, item) {
        winners_array.push( {name: 'fullname', value: item.data('fullname')} );  
    });
    
    console.log(winners_array);
    // ERROR in console log : item.data is not a function
    

  • Jquery: Select all H2 tags on page, copy the text of those H2 tags to a list
  • jQuery each() and load() ordering
  • Why would my find method return undefined?
  • Jquery if its the first time element is being clicked
  • each function in jquery condition
  • Multiple ajax calls inside a each() function.. then do something once ALL of them are finished?
  • 3 Solutions collect form web for “Using jQuery to get data attribute values with .each()”

    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')}
    });
    

    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>
    

    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);