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

257
Vistas
How to remove duplicate instances of class

In javascript, I am trying to apply an 'active' class upon clicking a button. However, I would then like to remove the class from the button which previously had it. I'm not sure how to best go about this. I was considering something involving a second loop after the click, but that seems somewhat convoluted, and like there's probably a better way. Here's the code I have to add the class, but again, not sure how to best go about removing it from the button to which it was previously applied.

const giftcards = document.querySelectorAll('.giftcard');

for(let giftcard of giftcards){
  giftcard.onclick = () => {
    giftcard.classList.add('active');
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If there is always at most one .giftcard with an active class you could query for that giftcard before setting active to the currently clicked one using document.querySelector('.giftcard.active') and utilize Optional chaining (?.) to remove the active class only if an element was found.

const giftcards = document.querySelectorAll('.giftcard');

for (let giftcard of giftcards) {
  giftcard.onclick = () => {
    document.querySelector('.giftcard.active')?.classList.remove('active');
    giftcard.classList.add('active');
  }
}
.active {
  color: red;
}
<div class="giftcard">card 1</div>
<div class="giftcard">card 2</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

<div>
  <button class="giftcard">Button 1</button>
  <button class="giftcard">Button 1</button>
  <button class="giftcard">Button 1</button>
</div>
<script>
  const giftcards = document.querySelectorAll(".giftcard");
  giftcards.forEach((giftcard) => {
    giftcard.addEventListener("click", () => {
      giftcardClick(giftcard);
    });
  });
  function giftcardClick(giftcard) {
    giftcards.forEach((giftcard) => {
      giftcard.classList.remove("active");
    });
    giftcard.classList.add("active");
  }
</script>
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