循环遍历节点列表 JS

Looping through a nodelist JS

本文关键字:JS 列表 节点 遍历 循环      更新时间:2023-09-26

我的问题是:我试图通过类热的节点列表。我想将他们的类名更改为"酷"。当 ibe 使用 for 循环时,似乎它是第二个 li 不会改变颜色。有谁知道我在这里犯了什么错误,第二个 li 元素不会改变颜色.

谢谢

var elements = document.getElementsByClassName('hot');
var i;
for(i = 0; i < elements.length; i++) { 
  elements[i].className = 'cool';
}
*{
  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;
}
<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>

getElementsByClassName返回一个活动节点列表。一旦你改变了一个元素的类,节点列表就会更新以反映这一点,所以你的索引将始终处于状态。

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

var elements = [].slice.call(document.getElementsByClassName('hot'));

演示

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

document.querySelectorAll('.hot');

演示