Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Oct 2002
    Thanked 0 Times in 0 Posts

    Problem with looping through objects!

    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.


  2. #2
    Regular Coder
    Join Date
    Jul 2002
    Kansas, USA
    Thanked 54 Times in 53 Posts
    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>


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts