P
P
Pavel Chuev2018-02-12 20:15:50
JavaScript
Pavel Chuev, 2018-02-12 20:15:50

How to properly make a dropdown div on click?

I have such html code (wiped unnecessary sections as unnecessary)

<div class="tab-pane" for="standart tabs_containers" id="tab0">
  <div class="effectiv_bar" style="width: 25%">25%</div>
  <div class="effectiv_color" style="width: 25%"></div>
  <div class="big_block">
    <button class="material_info">подробнее о материале</button>
  </div>
  <div class="desc">
    <ul style="padding: 0;">
тут какой-то текст
    </ul>
  </div>
</div>

I add the following styles to the "desc" block:
.desc{
       display: none;
}

And I catch clicks with the following js:
var acc = document.getElementsByClassName("material_info");
var i;
                        
for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
  this.classList.toggle("active");
        if (document.getElementsByClassName("desc")[i].style.display == "block") {
    document.getElementsByClassName("desc")[i].style.display = "none";
  } else {
    document.getElementsByClassName("desc")[i].style.display = "block";
  }
});
}

As a result, I get in the console: Cannot read property 'style' of undefined and the absence of the appearing block. Where is the mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-12
@AllDecay

The fact that the value of i at the moment of execution will be the same as at the moment of execution is an unfounded fantasy that does not correspond to reality. Now, if you declare i in the loop header using let - then yes, it will work. document.getElementsByClassName("desc")[i]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question