Thursday, March 31, 2011

Javascript function: nothing executes after a for(x in y) loop?

I can't seem to find the answer to this anywhere... I have a function that needs to set the bg color of two tables. Only the first table in the function is being affected. Is only one for loop allowed in a function? ...or is the 1st for loop maybe never exiting?

I can pretty much work around this by creating multiple functions but I really want to understand why this behaves the way it does!

Thanks!

Here is my simplified code:

function setColor()
{
  //This works
  var t1rows=document.getElementById("table1").getElementsByTagName("tr");
  var x;
  for (x in t1rows)
  {
    t1rows[x].style.backgroundColor='yellow';
  }

  //this one does not work
  var t2rows=document.getElementById("table2").getElementsByTagName("tr");
  var y;
  for (y in t2rows)
  {
    t2rows[y].style.backgroundColor='yellow';
  } 
}
From stackoverflow
  • getElementsByTagName() returns a NodeList object, and for-in will iterate its properties which you don't want. You want to use a straight for loop:

    for(var i=0; i < t2rows.length; i++) {
        t2rows[i].style.backgroundColor='yellow';
    }
    

    You're not getting to the second loop because the first is failing when it tries to access a non-existent style property on one of the NodeList's members.

    JB : Wouldn't that cause the 1st one to fail as well? ..or is this preventing the 1st loop from exiting?
    Crescent Fresh : See edited answer
    JB : OK, that makes sense. I tried using straight for loops and it works now. Thanks!

0 comments:

Post a Comment