简体   繁体   English

删除除首先使用纯JS之外的所有类

[英]Remove all classes except first using pure JS

I am trying to remove all classes except the fist one. 我正在尝试删除除拳头课程以外的所有课程。

html: 的HTML:

<div class="note">1</div>
<div class="note">1</div>
<div class="note">1</div>
<div class="note">1</div>

Js: Js:

for (var item of document.querySelectorAll("div.note(not:first-of-type"))) {
    item.classList.remove('note');
}

Use :not(:first-of-type) : 使用:not(:first-of-type)

 for (var item of document.querySelectorAll("div.note:not(:first-of-type)")) { item.classList.remove('note'); } 
 .note { color: yellow; } 
 <div class="note">1</div> <div class="note">2</div> <div class="note">3</div> <div class="note">4</div> 

Just loop and check the index like so: 就像这样循环并检查索引:

Array.from(document.querySelectorAll("div.note")).forEach((div, ind) => {
    if (ind != 0) {
        div.classList.remove("note");
    }
});

you can simply use for loop also: 您还可以简单地使用for循环:

var array = document.querySelectorAll("div.note");
for(let i =1; i<array.length; i++){
    array[i].classList.remove('note')
}

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

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