简体   繁体   English

如何在没有 JQuery 的情况下从元素的兄弟元素中删除类?

[英]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?在 JQuery 中它很简单,但是如何在纯 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.您可以在单击事件中使用循环从所有元素中删除active类,然后再次将其设置在单击的元素上。

 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/小提琴: 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).在严格模式下,您应该将[...el.parentElement.children]切换到Array.from(el.parentElement.children)以避免对数组开始一行的抱怨(尽管我不确定为什么会有帮助)。

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.使用previousSiblingnextSibling遍历它,并使用classList.remove删除一个类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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