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

147
Vistas
How to remove all instances of a class when adding it to a new object in Javascript

Trying to create an active state on the most recently clicked navigation bar button. Currently it will add the class to each item selected but the for...of loop doesn't seem to remove the class.

The nav bar is dynamically made with the following code:

function buildNavBar(){
  for (section of sections){
    numberOfSection = section.getAttribute('data-nav');
    idOfSection = section.getAttribute('id');
    navBarList = document.createElement('li');
    //Uses template literal strings to present the section names in the nav bar
    navBarList.innerHTML = `<a class='menu__link' href='#${idOfSection}'>${numberOfSection}</a>`;

    navBar.appendChild(navBarList);
  }
}
document.getElementById('navbar__list').addEventListener("click", function(event){
  function removeStyle(){
    let funcElem_Style = 'funcElemStyle';
    let menuLinks = document.querySelectorAll('menu__link')
    menuLinks = document.getElementsByClassName('funcElemStyle')
    for(menuLink of menuLinks){
      menuLink.classlist.remove('funcElemStyle')
    }
  }
  event.target.classList.add("funcElemStyle");
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Don't use for...of to iterate over live HTMLCollections like what getElementsByClassName returns. The reason is that in that loop you are executing code which leads to the element being removed from the live collection instantly, which in turn for the for...of (which internaly works index-based) means that the next element to iterate over actually is the element after the next one, leading to a loop that affects only every 2nd element in the collection.

Instead, spread the result into an array and iterate that.

Next, these two lines don't make sense:

let menuLinks = document.querySelectorAll('menu__link')
menuLinks = document.getElementsByClassName('funcElemStyle')
  1. document.querySelectorAll('menu__link') would find <menu_link> elements (which would be invalid elements and your page probably doesn't have these). You probably meant to select all elements with that CSS class like this: document.querySelectorAll('.menu__link')?

  2. In the next line you directly overwrite what you just tried to select from the DOM: menuLinks = document.getElementsByClassName('funcElemStyle').

  3. Inside your anonymous event listener function you declare another function removeStyle() which you never call.

These things said, this is probably what you are after:

document
  .getElementById('navbar__list')
  .addEventListener('click', function(event) {
    for (const menuLink of [...document.querySelectorAll('.menu__link')]) {
      menuLink.classlist.toggle('funcElemStyle', event.target === menuLink)
    }
  }
);
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