Person
Person

Reputation: 2269

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

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';
};

Upvotes: 6

Views: 18931

Answers (4)

SamGoody
SamGoody

Reputation: 14508

A generic function to set only one active element would be:

const setActive = el => {
    [...el.parentElement.children].forEach(sib => sib.classList.remove('active'));
    el.classList.add('active')
    }

In your example:

let spans = [...document.body.querySelectorAll('.controllers > span')];
spans.forEach(el => el.addEventListener('click', e => setActive(el)))

Fiddle: https://jsfiddle.net/9j1qguac/

Update: At one point, browsers expected Array.from(el.parentElement.children) instead of [...el.parentElement.children]. Both are now supported, but if you start a row with a bracket, the previous row needs a semicolon. (eg a = b \n [1].map... will be treated as a = (b[1]).map....

Upvotes: 10

Simon Angatia
Simon Angatia

Reputation: 860

Remove a class from an element siblings

let elem = document.getElementById('id');
let siblings = elem.parentElement.children;
  for(let sib of siblings) {
      sib.classList.remove('active')
      }

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122085

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>

Upvotes: 11

gurvinder372
gurvinder372

Reputation: 68433

To remove a class from sibling

var el = document.getElementById( "two" );
var one = el.previousSibling();
one.classList.remove("active");

use previousSibling or nextSibling to traverse to it, and use classList.remove to remove a class.

Upvotes: 3

Related Questions