1

I have nested two for loops like below. But the inner loop stops the outer loop in the first occurence. On execution,the below code gives only my 13th row in grey color where the expected behaviour is to see the 13th,14th and 15th row in grey color.

 var rows = document.getElementsByTagName("tr");
 for(var i = 0, max = rows.length;i < max;  i++)
 {

     var cells = rows[i].getElementsByTagName("td");
     if (rows[i].cells[4].innerHTML == "Asset Removed")
      {
        for(var inner = 0, max = rows[inner].cells.length;inner < max;  inner++)
         {
         cells[inner].style.backgroundColor = "grey";
         }

      }
 }

Any ideas?

2
  • 3
    Name max in the inner loop to something else. Commented Jun 18, 2014 at 7:15
  • @Kernel.. That worked.I dint notice that variable actually.Thank You. Commented Jun 18, 2014 at 7:17

2 Answers 2

2
for(var i = 0, max = rows.length;i < max;  i++)
    for(var inner = 0, max = rows[inner].cells.length;inner < max;  inner++)

The max variable in the inner loop is the same as in the outer loop, hence overwriting its values, thus causing the i < max end condition to become unreliable.

Sign up to request clarification or add additional context in comments.

Comments

2

You are using same variable in inner and outer loops. in javascript last assigned value is taken by variable as final value so change the inner loop max variable to some another name. try this one.

var rows = document.getElementsByTagName("tr");
 for(var i = 0, max = rows.length;i < max;  i++)
 {

     var cells = rows[i].getElementsByTagName("td");
     if (rows[i].cells[4].innerHTML == "Asset Removed")
      {
        for(var inner = 0, max1 = rows[inner].cells.length;inner < max1;  inner++)
         {
         cells[inner].style.backgroundColor = "grey";
         }

      }
 }

I have changes the inner loop max variable to max1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.