Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

372
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda