最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to remove class from siblings of an element without JQuery? - Stack Overflow

programmeradmin4浏览0评论

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

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';
};
Share Improve this question asked Oct 20, 2016 at 11:28 PersonPerson 2,26910 gold badges32 silver badges62 bronze badges 1
  • have a look at this: classlist – Kevin Kloet Commented Oct 20, 2016 at 11:30
Add a comment  | 

4 Answers 4

Reset to default 11

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/

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....

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

发布评论

评论列表(0)

  1. 暂无评论