Earthling Earthling - 2 months ago 6
Javascript Question

Reading the HTML Children of a <UL> collection

I'm trying to retrieve all the

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

HTML:

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


Javascript:

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

Answer

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++) {
  console.log(children[i]);
  // Do stuff
}

Fiddle

Comments