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 class from Button 1 when clicking on Button 2 - Vanilla JS

I am trying to make a highlight effect on Button 1 (bold and blue text with a css class). But of course the class should be removed from Button 1 when i click on another Button in the Menu.

let buttons = document.querySelectorAll(".ef-button");

for (let i = 0; i < buttons.length; i++) {

   buttons[i].addEventListener("click", function () {

      if (buttons[i].classList.contains("active-element")) {
         buttons[i].classList.remove("active-element");
      } else {
         buttons[i].classList.add("active-element");
      }

   })

}

This is what i wrote. I can click on every button to highlight it, but when i click on another button it does not remove the class from the first button... Anyways, i can click on a already highlighted button to remove the class again.

What i need is like a "reset" that removes the class from the button i clicked on.

enter image description here

When i click on Buttons:

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

this way:
for those who want to avoid searching in the MDN Doc1

document
.querySelectorAll('.ef-button')
.forEach( (btClickEv,_,buttons) =>
  {
  btClickEv.onclick = () =>
    buttons.forEach(bt=>bt.classList.toggle('active-element',bt===btClickEv))
  })
.ef-button       { background : pink; }
.active-element  { background : green; }
<button class="ef-button"> bt1 </button> 
<button class="ef-button"> bt2 </button> 
<button class="ef-button"> bt3 </button> 
<button class="ef-button"> bt4 </button> 
<button class="ef-button"> bt4 </button> 

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