I'm trying to connect an array of objects referring to SVG Icons in a for loop to an array of matching content by letting the for loop index act as a pairing mechanism. Both Array's log as identifying all the relevant objects but when I call the panel[i] changes I get that panel[i] is undefined? acc[i] seems to work just fine inside the for loop. How can I make sure the acc[i] event listeners pair up with their corresponding index position panels to then control css on the panels to change display from hidden to block?
Thanks!
const acc = document.querySelectorAll(".fas.fa-plus-circle.fa-3x");
const panel = document.querySelectorAll(".panel");
let i;
console.log(acc);
console.log(panel);
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
console.log(panel[i]);
if (panel[i].style.display === "block") {
panel[i].style.display = "none";
} else {
panel[i].style.display = "block";
}
});
}
Because you have declared i outside the for loop, there is only one i variable, and it will have become equal to acc.length when the loop has completed. So when you click, and the event handler is executed, that value of i is not what you want to have there.
To solve this, make i a block-scoped variable:
for (let i = 0; i < acc.length; i++) {
Now each iteration of the loop will have its own i variable, which will retain its value. There will be an i that is 0, another that is 1, ...Etc. As a consequence the event handlers will each access the right i having the expected value.