Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
Accordion For Loop JS Selector

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";
    }
  });
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!