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

问题描述 投票:1回答:3

我试图删除除第一个类以外的所有类。

HTML:

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

JS:

for (var item of document.querySelectorAll("div.note(not:first-of-type"))) {
    item.classList.remove('note');
}
javascript html html5 loops webpage
3个回答
5
投票

使用: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>

1
投票

只需循环并检查索引,如下所示:

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

1
投票

你也可以简单地使用for循环:

var array = document.querySelectorAll("div.note");
for(let i =1; i<array.length; i++){
    array[i].classList.remove('note')
}
© www.soinside.com 2019 - 2024. All rights reserved.