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

1

How to access the data-opened property of each div that is inside 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 ?
    }
    
asked by anonymous 08.06.2018 / 21:45

3 answers

2

Do you need this FOR same? Only with 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'));
}
    
08.06.2018 / 21:50
1

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

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

i <= bares.length is now incorrect. You should only use < (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>
    
08.06.2018 / 22:01
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><divclass='bares'data-opened=1></div><divclass='bares'data-opened=2></div><divclass='bares'data-opened=3></div><divclass='bares'data-opened=4></div>

Makeasmallchangeonyourforfori<bares.lengthandthenthroughtheindexonlyaccessthepropertythrough attr :

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