循环遍历节点列表 JS

Chr*_*eas 1 html javascript css

我的问题是:我正在尝试通过 Hot 类的 NODELIST 。我想将他们的 className 更改为 'cool' 。当我使用 for 循环时,它的第二个 li 似乎没有改变颜色。有谁知道我在这里犯了什么错误,第二个 li 元素没有改变颜色。

谢谢

var elements = document.getElementsByClassName('hot');
var i;

for(i = 0; i < elements.length; i++) { 
  elements[i].className = 'cool';
}
Run Code Online (Sandbox Code Playgroud)
*{
  box-sizing: border-box;
}
.hot {
  background-color: red;
  border: 1px solid black;
  padding: 10px;
  margin-top: 1px;
  font-size: 25px;
  list-style-type: none;
}

.cool {
  background-color: blue;
  padding: 10px;
  color: white;
  font-size: 25px;
}
Run Code Online (Sandbox Code Playgroud)
<html>
  <body>
   <div id="page">
      <h1 id="header">List</h1>
      <h2>Buy Greoceries</h2>
      <ul>
         <li id="one" class="hot"><em>Fresh</em>figs</li>
         <li id="two" class="hot">pine nuts</li>
         <li id="three" class="hot">honey</li>
         <li id="four">balsamic vinegear</li>
     </ul>
   </div> 
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 5

getElementsByClassName返回活动节点列表。一旦您更改了一个元素上的类,节点列表就会更新以反映这一点,因此您的索引将始终消失。

缓解这种情况的一种方法是使用以下方法将节点列表转换为静态节点列表Array.slice.call:

var elements = [].slice.call(document.getElementsByClassName('hot'));
Run Code Online (Sandbox Code Playgroud)

演示版

正如您所指出的,另一种方法是使用document.querySelectorAll它返回静态节点列表:

document.querySelectorAll('.hot');
Run Code Online (Sandbox Code Playgroud)

演示版