Maria Jane Maria Jane - 2 months ago 5
Javascript Question

$.each doesn't work with jquery selector?

I have DOM like this

<div data-id="1" class="box_album_item"></div>
<div data-id="2" class="box_album_item"></div>
<div data-id="3" class="box_album_item"></div>


and I uses $.each

$.each('.box_album_item',function(i,val){
console.log($(this).attr('data-id'));
})


but I got error of

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in .box_album_item

Answer

You need to use it as a jQuery collection's function:

$('.box_album_item').each(function(i, val) {
  console.log($(this).attr('data-id'));
});

Always please make sure you read the documentation and examples before asking.

Comments