-1

I'm a newbie on JavaScript. I can't understand why if I write

document.getElementById('btn').addEventListener('click', function(){
  for (i=0; i<=10; i++){
    let writeNumber = document.getElementById('paragraph');

    writeNumber.innerHTML = i;
    
  }
})

I read only the last number, in this case '10', and if i write

document.getElementById('btn').addEventListener('click', function(){
  for (i=0; i<=10; i++){
    document.writeln(i);
  }
})

I can read all the numbers required. Thanks and sorry if this seems like a trivial question

GiulioM
  • 1
  • 1

1 Answers1

0
document.getElementById('btn').addEventListener('click', function(){
  for (i=0; i<=10; i++){
    let writeNumber = document.getElementById('paragraph');

    writeNumber.innerHTML = i;
    
  }
})

The above code will replace the content of the paragraph element with 10.

You can modify it to view all the numbers as below

document.getElementById('btn').addEventListener('click', function(){
  for (i=0; i<=10; i++){
    let writeNumber = document.getElementById('paragraph');

    writeNumber.innerHTML += `${i} `;
    
  }
})
document.getElementById('btn').addEventListener('click', function(){
  for (i=0; i<=10; i++){
    document.writeln(i);
  }
})

The code appends to the document with a new line character everytime it is called.

document.writeln(i) -> This only works on the main document and everything will be removed from the DOM. (So don't use this)

  • Thanks! After having read the operator +=, I found [link](https://stackoverflow.com/questions/32957729/what-is-in-javascript) and understand. – GiulioM Jan 18 '22 at 13:56