How to remove the active class from all children in a parent using Javascript
You are not removing the active
class from all elements when click
event is triggered. So, what you can do is to loop over again to all the div
and remove the active
class on click
event. I have created a custom function removeClass()
that removes the active
class on click
event.
var elements = document.querySelectorAll('.tab');
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('active');
elements[i].onclick = function (event) {
console.log("ONCLICK");
//remove all active class
removeClass();
if (event.target.innerHTML === this.innerHTML) {
this.classList.add("active");
}
}
}
function removeClass(){
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('active');
}
}
.active{
color: green;
}
<div class="tab-div">
<div class="tab">default</div>
<div class="tab" >hover</div>
<div class="tab">active</div>
</div>
I suppose it depends how many div
s you will ultimately have, and if only one div
should be active at a time, but I think it would be more efficient to just find the active div
and remove the class from that one rather than looping through all of them e.g.
var oldActiveElement = document.querySelector('.active');
oldActiveElement.classList.remove('active');
var newActiveElement = event.target;
newActiveElement.classList.add('active');