Search code examples
javascriptfor-loopwhile-loopconsoleinnerhtml

Output the results of loops to .innerHTML


I have looked at other answers to the questions that are similar and either my brain is too tired or the javascript is too complex for me to understand, or I'm just too dumb. I'm quite new and have limited understanding so far. I'm trying to understand loops and would like the output of the loops to be outputted to my div container, however when I do, they only run one instance of the loop (presumably the final iteration) rather than showing the whole thing as in the console. Two examples are below:

var x = 0;
while (x < 5) {
    console.log("Hello World")
      // document.getElementById('output').innerHTML = "Hello World";
      // Why wont it output this 5 times but will log to the console 5 times?
    x++
  }

// For Loop

for (var i = 0; i < 5; i++)
{

console.log("Hello World with 'for loop'");
  // document.getElementById('output').innerHTML = "Hello World";
  // Same with this one...
  }

Solution

  • Just replace with this

    document.getElementById('output').innerHTML += "hello world"