Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the active class from all children in a parent using Javascript

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");
        }
    }
}
like image 834
Roster Avatar asked Mar 22 '18 08:03

Roster


2 Answers

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>
like image 144
Ankit Agarwal Avatar answered Nov 09 '22 01:11

Ankit Agarwal


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');
like image 39
Code_Frank Avatar answered Nov 08 '22 23:11

Code_Frank