<body> <button class="rating">A</button> <button class="rating">B</button>
const buttonList = document.querySelectorAll(".rating");
buttonList.forEach((element) =\> {
element.addEventListener("click", function () {
document.querySelector(".rating").classList.remove("active");
element.classList.add("active");
});
});
.active { background-color: aqua; }
I wanted that, when you click a button it receives a class called "active", and the others buttons if they have that active class, it should been removed. But when I click the B button, the active class of the A button is removed, but when I click the A button the active class still exists in the B button.
>Solution :
document.querySelector(".rating") only matches the first element. So you are always selecting the first rating element and removing a class it may or may not have.
If only one element can be selected, select the one with the class.
const prevSelected = document.querySelector(".rating.selected");
if (prevSelected) {
prevSelected.classList.remove("active");
}
It can also be written as
document.querySelector(".rating.selected")?.classList.remove("active");