-1

Why document.getElementById(“demo”).innerHTML = Math.ceil((Math.random()*10)-1); only prints 1 number?

function myFunction() {
  var bbb = document.getElementById("ilgis").value;

  for (i = 0; i <= bbb; i++) {

    //document.writeln(aaa);
    document.getElementById("demo").innerHTML = Math.ceil((Math.random() * 10) - 1);

  }
}
<input type="number" id="ilgis" value="123">

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>
R3tep
  • 12,512
  • 10
  • 48
  • 75
AndriusJ
  • 9
  • 6

1 Answers1

1

Because you are replacing the innerHTML all the time, not adding something to it.

To add content, use += instead of just =:

function myFunction() {
  var bbb = document.getElementById("ilgis").value;

  for (i = 0; i <= bbb; i++) {

    //document.writeln(aaa);
    document.getElementById("demo").innerHTML += Math.ceil((Math.random() * 10) - 1);

  }
}
<input type="number" id="ilgis" value="123">

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

EDIT:

As @Robin Zigmond stated, it would actually be better to construct a string and append that string to innerHTML only once after the loop has finished to save performance:

function myFunction() {
  var bbb = document.getElementById("ilgis").value;

  var numbers = "";
  for (i = 0; i <= bbb; i++) {

    //document.writeln(aaa);
    numbers += Math.ceil((Math.random() * 10) - 1);

  }
  document.getElementById("demo").innerHTML = numbers;
}
<input type="number" id="ilgis" value="123">

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>
CodeF0x
  • 2,624
  • 6
  • 17
  • 28
  • 1
    Using `+=` on `innerHTML` is an antipattern - you're doing an expensive DOM update each time through the loop, while throwing away the previous HTML. Just use the loop to construct a string, and update the DOM once when it's complete. – Robin Zigmond Feb 20 '19 at 10:42
  • @RobinZigmond Didn't think about that. Would using `+=` with `textContent` / `innerText` be fine? – CodeF0x Feb 20 '19 at 10:44
  • Not sure, it's probably less expensive than innerHTML, but I doubt there's any advantage to just doing the update once after the loop. – Robin Zigmond Feb 20 '19 at 10:48
  • There's more information here btw: https://stackoverflow.com/questions/11515383/why-is-element-innerhtml-bad-code – Robin Zigmond Feb 20 '19 at 10:51
  • @RobinZigmond Thanks, that's really helpful! – CodeF0x Feb 20 '19 at 10:52
  • @AndriusJ You're welcome! Please consider marking my answer as accepted (the little tick next to the vote count). That makes it easier for future users to get an answer if they have the same problem :). – CodeF0x Feb 20 '19 at 12:20