Gil Gil - 7 months ago 11
Javascript Question

jQuery, .data('X') returns one value instead an array

I have this problem.

$(".myClass");


returns

[
<div class='myClass' data-hotel='1' style='myStyle'></div>
<div class='myClass' data-hotel='2' style='myStyle'></div>
<div class='myClass' data-hotel='3' style='myStyle'></div>
]


why then
$(".myClass").data('hotel');
only returns '1'?

i tried
$(".myClass").data();
but returns
Object {hotel: 1}

Answer

As per docs data(key) returns first element value :

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

Use map() to iterate over elements and return required data inside callback . Get the result array using get().

var res = $(".myClass").map(function() {
  return $(this).data('hotel');
}).get();

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='myClass' data-hotel='1' style='myStyle'></div>
<div class='myClass' data-hotel='2' style='myStyle'></div>
<div class='myClass' data-hotel='3' style='myStyle'></div>