Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the buttons are not removing active state when clicking another button?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading