JQuery, .data ('X') returns a single value instead of 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');returns only "1"?

I tried $(".myClass").data();but returnsObject {hotel: 1}

+4
source share
3 answers

According to the docs, it returns the value of the first element: data(key)

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

Use to iterate over items and return the required data inside the callback. Get an array of results with . map() 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>
Run codeHide result
+2

var arr = [];
var div = $('.myClass')
$.each(div, function() {
  arr.push($(this).data('hotel'))
})

console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.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>
Hide result

div

0

.each -

var values = [];
$('.myClass').each(function(i, obj) {
   values.push(obj);// can also use attr data-hotel
});

, .

0

All Articles