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

255
Views
Cómo eliminar instancias duplicadas de clase

En javascript, estoy tratando de aplicar una clase 'activa' al hacer clic en un botón. Sin embargo, me gustaría eliminar la clase del botón que la tenía anteriormente. No estoy seguro de cuál es la mejor manera de abordar esto. Estaba considerando algo que involucrara un segundo bucle después del clic, pero eso parece algo complicado, y probablemente haya una mejor manera. Aquí está el código que tengo para agregar la clase, pero nuevamente, no estoy seguro de cuál es la mejor manera de eliminarlo del botón al que se aplicó previamente.

 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

Si siempre hay como máximo una tarjeta de .giftcard con una clase active , puede consultar esa tarjeta de regalo antes de configurarla como active en la que se ha hecho clic actualmente usando document.querySelector('.giftcard.active') y utilizar el encadenamiento opcional (?.) para eliminar la clase active solo si se encontró un elemento.

 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!