4

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}

1
  • you need to iterate through each element Commented May 11, 2016 at 3:44

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

@Gil : glad to help :)
1

You need to execute .each loop for retrieving all values and can push these into an array -

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

Hope this will help you.

Comments

0

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>

Iterate through each div

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.