I have a function to add a class civil-active to the label that is clicked. When the next label is clicked the class is added to it too, naturally. But I want the class civil-active to be there only on the clicked label and get it removed from its previous and next sibling if present.
the code that is adding the class is
js
var labels = document.getElementsByTagName("label");
for (let i = 0; i < labels.length; i++) {
labels[i].addEventListener("click", addclass);
}
function addclass(event) {
event.target.classList.add("civil-active");
}
Please suggest me what should I do
In the event handler, find the element having the class and remove it.
function addclass(event) {
// Those lines will remove the class on the element that has it (if there is one)
let active = document.querySelector(".civil-active")
if(active){
active.classList.remove("civil-active");
}
event.target.classList.add("civil-active");
}