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

379
Views
JS Accordion - replacing a traditional for loop with forEach

So as I've slowly been learning JS I've been going through my site to improve any previous code.

One thing I've been doing lately is replacing for loops with forEach and so far all good apart from one which I can't figure out. It's for an accordion which closes one as another opens, but also scrolls the current one into view (it's for a mobile footer menu).

The top first for loop I can solve no problem, but it's the second one in that I'm struggling with and not even sure if it even can be done with forEach:

var acc = document.getElementsByClassName('footer-accordion');
var i;

for (i = 0; i < acc.length; i++) { // I can replace this one with forEach no problem
    acc[i].addEventListener('click', function() {
        this.classList.toggle('active');
        var panel = this.nextElementSibling;
        if (panel.style.display === 'block') {
            panel.style.display = 'none';
        } else {
            panel.style.display = 'block';
            for (let j = 0; j < acc.length; j++) { // This is the one I am struggling on!!
                if (this.classList != acc[j].classList) {
                    acc[j].classList.remove('active');
                    acc[j].nextElementSibling.style.display = 'none';
                    panel.scrollIntoView({
                        block: 'end',
                        behavior: 'smooth'
                    });
                }
            }
        }
    });
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Is something like this not working for you? can you share your html to help with testing?

acc.forEach((current)=>{ 
                if (this.classList != current.classList) {
                    current.classList.remove('active');
                    current.nextElementSibling.style.display = 'none';
                    panel.scrollIntoView({
                        block: 'end',
                        behavior: 'smooth'
                    });
                }
            })

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!