Jamie Kitson Jamie Kitson -4 years ago 70
HTML Question

JavaScript Traverse Table Issue

Why does this script bail out (IE) or stick (FF) at the first table cell containing text that it finds?

<script type="text/javascript">
function CheckChildren(obj)
alert(obj.id + ' ' + obj.tagName + ' ' + obj.childNodes.length);
for ( i = 0; i < obj.childNodes.length; i++)
return false;

<table id="table">
<tr id="a"><td id="b">b</td><td id="c">c</td></tr>
<tr id="d"><td id="e">e</td><td id="f">f</td></tr>
<input type="button" onclick="CheckChildren(document.getElementById('table'))" value="click">

Answer Source

Try putting the word "var" before the "i" in your for loop.

  for ( var i = 0; i < obj.childNodes.length; i++)

Without that, your code is referring to a global variable "i", so each recursive iteration sets it back to zero.

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