简体   繁体   English

遍历节点列表JS

[英]Looping through a nodelist JS

My question is : iam trying to get through the NODELIST of class Hot . 我的问题是:iam试图通过Hot类的NODELIST。 And i want to change their className to 'cool' . 我想将其className更改为'cool'。 When iam using the for loop it seems that its the second li doesn't change color. 当iam使用for循环时,似乎第二个li不变。 Does anyone know what is my mistake here and the second li element doesnt change color . 有谁知道我在这里的错误,第二个li元素没有改变颜色。

Thank you 谢谢

 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 returns a live node list. getElementsByClassName返回活动节点列表。 Once you've changed the class on one element the node list updates to reflect this so your index will always be out. 一旦在一个元素上更改了类,节点列表就会更新以反映这一点,因此索引将始终不存在。

One way to mitigate this is to convert the node list to a static node list using Array.slice.call : 减轻这种情况的一种方法是使用Array.slice.call将节点列表转换为静态节点列表:

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

DEMO DEMO

Another way, as you point out, is to use document.querySelectorAll which returns a static node list: 如您所指出的,另一种方式是使用document.querySelectorAll返回静态节点列表:

document.querySelectorAll('.hot');

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM