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?

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

Leave a Comment