SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member Brendan Short's Avatar
    Join Date
    Aug 2012
    Location
    Southampton, United Kingdom
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Strange error - Using loop to modify elements, only changes last element. Any ideas?

    Hi there,

    I'm new to javascript and I was just wondering if anyone could tell me why my code is behaving like this?

    Code:
    var canvas = new Array();
    			resultsHTML = '';
    			for(i=0;i<results.length;i++){
    				resultsHTML = resultsHTML + '<h1>Item ' + i + '</h1>' ;
    				resultsHTML = resultsHTML + '<div id="' + i + '" width="250" height="25"></div>' ;
    				document.getElementById("content").innerHTML =  resultsHTML;
    				
    				document.getElementById(i).innerHTML = "Test - This only appears in the last item";
    				canvas[i]= document.createElement('canvas');
    				canvas[i].width = 240;
    				canvas[i].height = 40;
    				canvas[i].id = "canvas-" + i;
    				document.getElementById(i).appendChild(canvas[i]);
    	
    			}
    The "Test - This only appears in the last item" and canvas only appears on the last iteration - I'm positive I'm doing something really stupid here, could anyone fill me in?

    Cheers!

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,826
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    document.getElementById("content").innerHTML = resultsHTML;

    overwrites the content of whatever has id="content" each time through the loop. This will happen so fast you'll only see the last value


    document.getElementById(i).innerHTML

    is meaningless where i is the loop counter as ids must start with a letter
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Member Brendan Short's Avatar
    Join Date
    Aug 2012
    Location
    Southampton, United Kingdom
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the reply - I'll try to think of a different way of updating the HTML. Is there a way to append/add HTML to a string until the loop has finished rather then updating the page every time?

  4. #4
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,826
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Use += in place of = to append to a text string instead of replacing it.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  5. #5
    SitePoint Addict bronze trophy AllanP's Avatar
    Join Date
    Sep 2010
    Location
    Australia
    Posts
    298
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    The main problem with your script is that it tries to write to "content" before the page has loaded, which means that it is not available. You are also trying to use results.length when it doesn't exist, and to set the width and height of the divs without using a style attribute.

    The following script addresses these shortcomings and turns your code into a function that runs on page load. It also appends the canvas to each div after the divs have been created. The last line on the page has been placed into <p> tags below the divs to avoid overwriting the canvas element in the last div.

    You can see the <canvas> elements inside each div if you inspect the DOM using firebug or similar.

    Code:
    <!DOCTYPE HTML>
    <!-- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -->
    <html>
    
    <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Strange error</title>
    <script type="text/javascript">
     var canvas = new Array(); // global                                     // added new global vars
     function init()
      { var resultsHTML = '';                                                      // must declare variable
        for(var i=0;i<3;i++)                                                         //<<<<< no result.length substituted 3
          { resultsHTML +='<h1>Item ' + i + '</h1>' ;
            resultsHTML +='<div id="x' + i + '" class="xDiv"></div>' ;           //<<<<<< added x to id generation and class to div
            // can't set width="250" height="25" need style 
            // can't write to content before page loads
           } 
           resultsHTML+='<p>Test - This only appears as the last item<\/p>\n';
           document.getElementById("content").innerHTML = resultsHTML;
          // 
           for(i=0;i<3;i++) 
            { var thisObj=canvas[canvas.length]= document.createElement('canvas');
              thisObj.width = "240"; thisObj.height = "40"; thisObj.id = "canvas-" + i;             
              document.getElementById("x"+i).appendChild(thisObj);	
           }     
      }	
    // ----------			
    window.onload=init;			
    </script>
    <style type="text/css">
    body { font-family:arial, helvetica, sans-serif; font-weight:bold; font-size:13px; color:#000; text-align:left; margin:3px 0px; }
    #wrap  { width:500px; height:300px; margin-left:20px;  }
    .xDiv { padding:2px; border:1px solid #00F; width:250px; height:25px;   }
    </style>
    </head>
    
    <body>
    
    <div id="wrap">
       <div id="content">
       <!-- will write to here -->
       </div>
    </div>
    
    </body>
    
    </html>

  6. #6
    SitePoint Member Brendan Short's Avatar
    Join Date
    Aug 2012
    Location
    Southampton, United Kingdom
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah awesome, solved the problem. Thanks guys, appreciate the help!


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
  •