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

时间:2019-03-01 06:51:07

标签: javascript html html5 loops webpage

我正在尝试删除除第一类之外的所有类。

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

3 个答案:

答案 0 :(得分: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 :(得分:1)

像这样循环并检查索引:

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

答案 2 :(得分:1)

您还可以简单地使用for循环:

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