Identifier 'i' has already been declared problem

Viewed 88

I try to do a accordion for display content and i get this problem on mi js code, I'm sure it's an easy problem to fix, but I can't see it right now, I need help to see it.

JS code:

var acc = document.getElementsByClassName("servicon-button");
var i;


for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}

My html of this:

<button class="servicon-button"> <img src="icons/computer.svg" alt=""> </button>
<div class="panel">
2 Answers

try declaring the i variable inside the for loop, putting the variable inside the for loop ensures that the variable is only used inside the loop which is a good thing, if you put it outside, it will mix with other variables in the code in the global scopes which can cause problems like reassigning or redeclaring variables

const acc = document.getElementsByClassName("servicon-button");

for (let i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    const panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}

sidenote : var is not really recommended, use const and let instead

Instead of declaring var i before the loop, declare it inside the for loop like this: for (let i = 0; i < acc.length; i++) { ... This is where the error is coming from.

Related