0

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
}
Julien
  • 2,616
  • 1
  • 30
  • 43
Jay
  • 4,873
  • 7
  • 72
  • 137

4 Answers4

2

In jquery use:

$(document).ready(function() {
    $("#new-ul input").each(function(){
        console.log($(this).val())
    });
});
P. Frank
  • 5,691
  • 6
  • 22
  • 50
1

You can easily achieve it like this

Array.prototype.map.call( document.querySelectorAll("#new-ul input"), function( element,index ){

    console.log( element.value );

});

Fiddle:http://jsfiddle.net/4n4dwqpt/

guramidev
  • 2,228
  • 1
  • 15
  • 19
1

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

reggaemahn
  • 6,272
  • 6
  • 34
  • 59
-1

Could be done by jquery $.each easily

$("#your-ul-id li").each(function(){ 
    console.log($(this)) 
});