简体   繁体   中英

Javascript for loop behaving strange

I have a for loop to loop through the node which is <ul> that has 5 <li> elements. I am trying to create a div for each of those li elements

When I try to append the li elements to div then the for loop is behaving strange

for (var i = 0; i < docNodes.children.length; i++) {
        var docs = document.createElement('div');
        docs.appendChild(docNodes.children[i]); //If this line is removed then it loops 5 times else it loops only 3 times
    }

Could someone let me know what is wrong with the code

The behavior isn't that weird. You're changing the length of docNodes.children in every iteration of the loop. For the next iteration, it checks the length again:

i | Length | i < length
0     5        true
1     4        true
2     3        true
3     2        false // Loop stops before the 4th iteration.

The reason the length is changing, is because docs.appendChild actually removes the target element from it's previous parent.

A way to work around this issue, it to iterate over the children in the opposite order:

for (var i = docNodes.children.length - 1; i >= 0 ; i--) {
    var docs = document.createElement('div');
    docs.appendChild(docNodes.children[i]);
}
i | Length | i >= 0
4     5       true
3     4       true
2     3       true
1     2       true
0     1       true
-1    0       false // Loop stops before the 6th iteration. 

As other point out you modify the length of the array during the loop. In JavaScript it's better to use Array.prototype.forEach instead of an old fashioned for loop.

For example:

docNodes.children.forEach(function (child) {
    var docs = document.createElement('div');
    docs.appendChild(child);
});

Try this. And apply similar logic into your code.

<div id="list"></div>

<script>
let children = ['1','2','3','4','5'];

for (var i = 0; i < children.length; i++) {
  var node = document.createElement("LI");
  var textnode = document.createTextNode(children[i]);
  node.appendChild(textnode);
  document.getElementById("list").appendChild(node);
}
</script>

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