View Full Version : Problem with looping through objects!

10-15-2003, 01:45 PM
I have a problem I'd be very glad if you could help me with!

I have a 12 TD-tags with ID and name set to "Output1", "Output2" etc.

It works fine to place data in there by using:
Output1.innerHTML = "test";

But I can't get my while statement to loop through all the TD's!

I would like to do this, but it doesn't work:

var i = 1;

while (i < 12)
Output[i].innerHTML = "test no " + i;
i= i+1;

How can I solve this? I've tried a numerous of different approaches.


10-15-2003, 05:13 PM
In order to change the contents of an HTML element like a TD, you'll need to use the DOM a bit.

Below is a modification of your example script. It uses document.getElementById() to retrieve a reference to each TD by its id. The i++; code is the same as i = i + 1; which can also be written as i += 1; The only other change was in the while condition: i < 12 only looped through Output11.

document.getElementById() is available in all current browsers and the only browser that's still got a large user-base that doesn't support it is NN4.

<script language="JavaScript" type="text/javascript">
function loop_td(){
var i = 1; var obj;
while ( i <= 12 ){
obj = document.getElementById("Output" + i);
obj.innerHTML = "test " + i;
<a href="javascript:loop_td();">Loop TDs</a>
<table border="1">
<td id="Output1"></td>
<td id="Output2"></td>
<td id="Output3"></td>
<td id="Output4"></td>
<td id="Output5"></td>
<td id="Output6"></td>
<td id="Output7"></td>
<td id="Output8"></td>
<td id="Output9"></td>
<td id="Output10"></td>
<td id="Output11"></td>
<td id="Output12"></td>