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

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

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 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