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?

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!

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

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?

Use += in place of = to append to a text string instead of replacing it.

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. :slight_smile:


<!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>\
';
       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>

Ah awesome, solved the problem. Thanks guys, appreciate the help!