Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

// 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
like image 976
Zabs Avatar asked Jan 23 '14 11:01

Zabs


People also ask

How get data attribute value in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.

How do you find the element based on a data attribute value?

Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.

What is the use of attr () method in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How can get li id value in jQuery?

Show activity on this post. $('#loadMore'). on('click', function () { var page = $('#page'); var msg = $('#loadMoreMsg'); alert($(this). attr('id')); return false; });


2 Answers

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>
like image 22
Vinay Avatar answered Sep 24 '22 22:09

Vinay


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')}
});
like image 151
adeneo Avatar answered Sep 22 '22 22:09

adeneo