JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops For Loops

Joss Paddock
Joss Paddock
5,022 Points

Why is it that when I try to preview my workspace I get only a blank browser page?

script.js file: ```var html = '';

for (var i = 1; i <= 10; i +=1 ) { html += '<div>' + i + '</div>'; } document.write(html);```

index.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Circles</title> <link rel="stylesheet" href="css/styles.css"> </head> <body id="color"> <script>src="js/script.js"</script> </body> </html>

Zack Jackson
Zack Jackson
30,197 Points

To post code to the forums, break the line after the ```

2 Answers

Joss Paddock
Joss Paddock
5,022 Points

Moving the > in my opening script tag did the trick. The rest is how the project came and shows up now in the browser the way it does in the video. I kept closing the workspace and reopening it thinking it was reset, but now I am thinking I was just reopening the same corrupted(by me) code from the previous session. So I have to remember to delete the workspaces if I get so stuck again. As far as your variation to the rest of the code it is beyond my comprehension level, though I appreciate your effort Many thanks!!

Zack Jackson
Zack Jackson
30,197 Points

The end ">" on your html script tag is in the wrong spot.

Once you fix that script tag, your actual javascript code is not doing exactly what you want it to. It's putting everything at the end of the body after your script tag because your code doesn't tell the loop where to inject the html. Also, the first returned value with your code is undefined, but I'm not sure why.

This is how I would do it. This could probably be refactored but hey it works.

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="UTF-8"> 
    <title>Circles</title> 
    <link rel="stylesheet" href="css/styles.css"> 
  </head> 

  <body id="color"> 
    <div id='app'>
    </div>
    <script src="js/script.js"></script> 
  </body> 
</html>
var container;
var div;

for (var i = 1; i <= 10; i +=1 ) { 
  div = document.createElement( 'div' );
  div.innerHTML = i ;
  container = document.getElementById('app');
  container.appendChild(div);
}