简体   繁体   中英

Looping through a nodelist JS

My question is : iam trying to get through the NODELIST of class Hot . And i want to change their className to 'cool' . When iam using the for loop it seems that its the second li doesn't change color. Does anyone know what is my mistake here and the second li element doesnt change color .

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. 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 :

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

DEMO

Another way, as you point out, is to use document.querySelectorAll which returns a static node list:

document.querySelectorAll('.hot');

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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