Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove class from siblings of an element without JQuery?

Tags:

javascript

I'm adding a class to an element and want to remove it from siblings. In JQuery it is simple, but how to do it the best way in plain JS? Here is an example of my code.

<div class="controllers">
  <span id='one' class='active'></span>
  <span id='two'></span>
  <span id='three'></span>
</div>

firstBtn.onclick = function() {
  slides[0].className = 'slide active';
  this.className = 'active';
};
like image 716
Person Avatar asked Oct 20 '16 11:10

Person


People also ask

How do you remove a specific class from all elements?

To remove all CSS classes of an element, we use removeClass() method. The removeClass() method is used to remove one or more class names from the selected element.

How do I remove a class from a DOM element?

To remove a class from an element, you use the remove() method of the classList property of the element.


1 Answers

You can use loop inside click event to remove active class from all elements and then again set it on clicked element.

var el = document.querySelectorAll('.controllers span');
for (let i = 0; i < el.length; i++) {
  el[i].onclick = function() {
    var c = 0;
    while (c < el.length) {
      el[c++].className = 'slide';
    }
    el[i].className = 'slide active';
  };
}
.active {
  color: red;
}
<div class="controllers">
  <span id='one' class='active'>Lorem</span>
  <span id='two'>Lorem</span>
  <span id='three'>Lorem</span>
</div>
like image 82
Nenad Vracar Avatar answered Sep 25 '22 19:09

Nenad Vracar