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

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

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