Results 1 to 3 of 3

Thread: for loop issue

  1. #1
    Join Date
    Mar 2009
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default for loop issue

    All,

    I'm having a bit of issue with a for loop.

    Code:
    for(i = 0; i < captionID.length; i++) {
    	
    	document.getElementById("captainContent").innerHTML = captionID[i];
    	
    }
    This returns only the last number in the caption[120] rather than printing
    captionID[0]
    captionID[1]
    captionID[2]
    captionID[3]
    etc

    Any ideas?

    Thanks,
    --thesprucegoose

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    This is not the ideal way, but the easiest to add to what you currently have:

    Code:
    document.getElementById("captainContent").innerHTML += captionID[i] + '<br>';
    I'll present a DOM solution (the preferred method) in a bit (when I have the time, if not sooner).
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Better:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
    <div id="captionContent"></div>
    <script type="text/javascript">
    (function(){
     var captionID = [], i = 0, b = document.createElement('br'),
     c = document.getElementById('captionContent'), l;
     captionID[0] = 'The';
     captionID[1] = 'Quick';
     captionID[2] = 'Brown';
     captionID[3] = 'Fox';
     l = captionID.length;
     for(i; i < l; ++i) {
      c.appendChild(document.createTextNode(captionID[i]));
      c.appendChild(b.cloneNode(false));
     }
    })();
    </script>
    </body>
    </html>
    Last edited by jscheuer1; 03-31-2009 at 07:43 PM. Reason: minor code improvements
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

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