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

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

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 Relatório

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