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');
}
}
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>
<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>