A loop that keeps incrementing until the variable is smaller that the length of the child nodes keeps crashing my page. Why?

I have this very simple loop that keeps crushing my page.

var listtest = document.getElementById("newlist");

for(var t = 0; t < listtest.childNodes.length; t++) { 
  var crash = document.createElement("a");
  var crashtext = document.createTextNode("some random text"+t);
  crash.appendChild(crashtext);
  listtest.insertBefore(crash, listtest.childNodes[t]);
}
<ul id="newlist">
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
</ul>

Every time I run this loop, my page crashes. I can’t even open the console. I know the issue has to be with the condition t < childNodes.length, because when I remove it, it doesn’t crash, but I can’t figure out what exactly is the problem with my condition, or code in general?

2 thoughts on “A loop that keeps incrementing until the variable is smaller that the length of the child nodes keeps crashing my page. Why?”

  1. By adding new elements to the DOM, you increase the listtest.childNodes.length by one, therefore it will never get to the last one because there will always be new ones created, you should copy the length in a variable loopCount before doing the loop:

    var listtest = document.getElementById("newlist");
    const loopCount = listtest.childNodes.length
    
    for(var t = 0; t < loopCount; t++) { 
      var crash = document.createElement("a");
      var crashtext = document.createTextNode("some random text"+t);
      crash.appendChild(crashtext);
      listtest.insertBefore(crash, listtest.childNodes[t]);
    }
    <ul id="newlist">
      <li>First</li>
      <li>Second</li>
      <li>Third</li>
    </ul>
    Reply
  2. Because you add one object to the list each loop you’ll never exit, which makes Js crash. I don’t know what you’re trying to do but maybe put listtest.childNodes.length into its own var and lopp until you reach that length instead?

    Reply

Leave a Comment