也許有人問過同樣的問題,但我沒有在可能已經有你的答案的問題中找到任何類似的結果,所以我會繼續問我的問題。我知道這是活着的列表,當第一個className將列表從3項改爲2。所以我現在是1,所以這就是爲什麼它跳過列表中的「第二項」。在循環中包含活動節點列表中的所有項目的最佳方式是什麼? (也許用一個靜態?)Javascript Live Nodelist Loop
var hotElements = document.getElementsByClassName("hot");
var i;
var len = hotElements.length;
for (i= 0; i < len ; i++) {
hotElements[i].className = "pink";
}
.hot {
background-color: red;
color: black;
font-size: 20px;
weight: 700;
}
.cool {
background-color: blue;
font-size: 25px;
}
.pink {
background-color: pink;
font-size: 35px;
<h1 id="header"> List King </h1>
<h2> Buy grocceries </h2>
<ul>
<li id="one" class="hot"> Fresh </li>
<li id="two" class="hot"> Fresh 1</li>
<li id="three" class="hot"> Fresh 2 </li>
<li id="one" class="cool"> Fresh </li>
<li id="two" class="cool"> Fresh 1</li>
<li id="three" class="cool"> Fresh 2 </li>
</ul>
只需更改類的第一要素列表:'hotElements [0] .className =「pink」;'迭代時。或者向後迭代,或者使用'querySelectorAll'來獲得一個靜態列表。 – Teemu
@Teemu然後,您也可以刪除'len'和'i'變量,並使用'hotElements [0]'作爲循環條件並使用'while'循環代替。 – Xufox
@Xufox Jup,這是可能的。 – Teemu