最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - For loop skips one after every other iteration - Stack Overflow

programmeradmin0浏览0评论

I have a list of HTML elements having class "black" (with some other classes). I want to convert the "black" to "white". I have written the following code.

var blacks = document.getElementsByClassName("black");
for (i = 0; i < blacks.length; i++)
    blacks[i].className = blacks[i].className.replace('black', 'white');

Interestingly, one element turns to white and one element is skipped until the end of elements. That is, elements with order of even numbers remain unchanged. What am I missing to convert all blacks?

I have a list of HTML elements having class "black" (with some other classes). I want to convert the "black" to "white". I have written the following code.

var blacks = document.getElementsByClassName("black");
for (i = 0; i < blacks.length; i++)
    blacks[i].className = blacks[i].className.replace('black', 'white');

Interestingly, one element turns to white and one element is skipped until the end of elements. That is, elements with order of even numbers remain unchanged. What am I missing to convert all blacks?

Share Improve this question asked Jul 3, 2012 at 18:13 sevenkulsevenkul 9661 gold badge8 silver badges14 bronze badges 1
  • 1 Don't forget to declare "i" with var! – Pointy Commented Jul 3, 2012 at 18:17
Add a ment  | 

2 Answers 2

Reset to default 8

document.getElementsByClassName returns a live NodeList that is automatically updated as you make changes to part of DOM it represents. You are treating it like a static list. You can do that by converting it to array:

var blacks = [].slice.call(document.getElementsByClassName("black"));

It just occurred to me that you could also:

var blacks = document.querySelectorAll(".black"); //NodeList but static

Further to the ment made about blacks being a live nodeList, you can avoid converting to an array, by simply decrementing through the loop:

var blacks = document.getElementsByClassName("black");
for (var i = blacks.length -1 ; i >= 0; --i) {
    blacks[i].className = blacks[i].className.replace('black', 'white');
}​

JS Fiddle demo.

发布评论

评论列表(0)

  1. 暂无评论