Adrian Enriquez
Adrian Enriquez

Reputation: 8413

How to get data attribute values from multiple class

How will I be able to get all the values of data-val by only using class not id? I can only get the first one. I think this can be accomplished by using loop, but I'm not really sure.

/* JS */

var dataValue = $('.test').data('val');
$('#result').append('Result: ' + dataValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- HTML -->
<div data-val="1" class="test"></div>
<div data-val="2" class="test"></div>
<div data-val="3" class="test"></div>

<div id="result"></div>

Not a duplicate of Using jQuery to get data attribute values with .each() because I'm not asking HOW to use .each() I'm asking WHAT to use and there is no each() function in the original post.

Upvotes: 1

Views: 6985

Answers (3)

David Kmenta
David Kmenta

Reputation: 850

It's not clear what do you want as a result. Counted values or values separated by something? This case gets every value into the array.

var result = [];
$(".test").each(function() {
    result.push($(this).data("val"));
});

$('#result').append('Result: ' + result.join(', '));

Upvotes: 1

Akshay
Akshay

Reputation: 14348

How about this

/* JS */

 $('.test').each(function(){
 var dataValue = $(this).data('val');
   $('#result').append(dataValue);
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- HTML -->
<div data-val="1" class="test"></div>
<div data-val="2" class="test"></div>
<div data-val="3" class="test"></div>

<div id="result"></div>

Upvotes: 3

mohamedrias
mohamedrias

Reputation: 18566

You need to iterate over the list to get:

Instead of modifying the DOM on each iteration, append it a string/array and then add it to the dom:

var array = [];
$(".test").each(function() {
    array.push($(this).data("val"));
});
$("#result").append("Results "+array.join(","))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- HTML -->
<div data-val="1" class="test"></div>
<div data-val="2" class="test"></div>
<div data-val="3" class="test"></div>

<div id="result"></div>

Upvotes: 7

Related Questions