简体   繁体   中英

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

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>

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/

In strict mode you should switch [...el.parentElement.children] to Array.from(el.parentElement.children) to avoid the complaint about an array starting a row (though I'm not sure why it helps).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM