How to access the data-opened property of each div that is inside an array ? Jquery/Javascript

Asked

Viewed 28 times

1

How to access the data-opened property of each div within an array ?

<div class='bares' data-opened=1></div>
    <div class='bares' data-opened=2></div>
    <div class='bares' data-opened=3></div>
    <div class='bares' data-opened=4></div>

    var bares = new Array();
    $('.bares').each(function(){
     bares.push($(this));
    })

    for (i = 0; i <= bares.length; i++){
    // como exibir alert da propriedade data-opened de cada div ?
    }

3 answers

2


You need this FOR really? Only with the each you get what you want.

var bares = new Array();

$('.bares').each(function(){
    var opened = $(this).data('opened');
    alert(opened);
});

If you really need to...

var bares = new Array();

$('.bares').each(function(){
    bares = bares.push($(this));
});

for (i = 0; i <= bares.length; i++){
    alert(bares.data('opened'));
}

1

You can take the data-opened of each element added in the array in this way:

  bares[i].data('opened')
    ↑   ↑
array   índice

Now the i <= bares.length is incorrect. You should only use the < (and not <=) because the loop should go up to the size of the array - 1:

var bares = new Array();

$('.bares').each(function(){
   bares.push($(this));
})

for (i = 0; i < bares.length; i++){
   alert(bares[i].data('opened'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='bares' data-opened=1></div>
<div class='bares' data-opened=2></div>
<div class='bares' data-opened=3></div>
<div class='bares' data-opened=4></div>

0

$(document).ready(function() {
  var bares = new Array();
  $('.bares').each(function() {
    bares.push($(this));
  });
  for (i = 0; i < bares.length; i++) {
    console.log(bares[i].attr('data-opened'));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='bares' data-opened=1></div>
<div class='bares' data-opened=2></div>
<div class='bares' data-opened=3></div>
<div class='bares' data-opened=4></div>

Make a small change in your go to i < bares.length and then through the index only access the property through the attr:

for (i = 0; i < bares.length; i++){
        console.log(bares[i].attr('data-opened'));
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.