I have created 3 div having the same class in a parent , and on the child element i am adding the active class and on click of second child adding the active class again but this time i want to remove the active state for first element. How can i remove it in effective way?
Here is my code
<div class="tab-div">
<div class="tab">default</div>
<div class="tab" >hover</div>
<div class="tab">active</div>
</div>
Here is my javascript
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");
if (event.target.innerHTML === this.innerHTML) {
this.classList.add("active");
}
}
}
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 divs 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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With