Because you are overwriting the content of the element in each iteration, by assigning a new value to innerHTML
. You'd have to append instead:
document.getElementById('display').innerHTML += (i + " ");
// ^
which is the same as
document.getElementById('display').innerHTML =
document.getElementById('display').innerHTML + (i + " ");
And of course it would be much better if you just built the string in the loop and set the content after the loop:
var content = '';
for (i = x; i > 0; i--) {
content += (i + " ");
}
document.getElementById('display').innerHTML = content;
This way you avoid searching for the element in the document on every iteration. But .innerHTML
is only useful to some degree, you should also have a look at DOM manipulation functions (such as .appendChild
), once you are starting to do more evolved manipulations.