也许有人问过同样的问题,但我没有在可能已经有你的答案的问题中找到任何类似的结果,所以我会继续问我的问题。我知道这是活着的列表,当第一个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