Earthling Earthling - 1 year ago 58
Javascript Question

Reading the HTML Children of a <UL> collection

I'm trying to retrieve all the

child nodes of a Parent
node via a loop during runtime. However the loop runs forever causing the browser to immediately crash. What am I doing wrong?


<ul id="new-ul">
<li> <input value="323" /> </li>
<li> <input value="421" /> </li>
<li> <input value="547" /> </li>


//Attempting to retrieve each value in input fields of each <li> child
var idbox = document.getElementById("new-ul");
while (idbox.firstChild) {
//Browser crashes here

Answer Source

What you're doing wrong is creating an infinite loop because the condition for the while loop will always evaluate to true. Instead, you wanna do this

var parent = document.getElementById('new-ul');
var children = parent.children;
for (var i = 0; i < children.length; i++) {
  // Do stuff


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download