Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!