Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

384
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda