1

I want to print numbers from 1 to 100 using for loop in a specific div. But it print only last number.

I tried this code :

let numbering = document.querySelector("#numbering");
for (var i = 1; i <= 100; i++) {
  numbering.innerHTML = (i);
}
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Rehman
  • 23
  • 3
  • The issue with your code is that the innerHTML of the "numbering" div is being overwritten on each iteration of the loop. This means that only the last value of i, which is 100, is left in the div. – Lalit Tyagi Jan 20 '23 at 05:46

3 Answers3

1

The issue is that you're overwriting the last number you wrote. Instead of using the = operator, you should use += to append to the current content. Although, as double-beep pointed out in a comment, it is better to use .insertAdjacentHTML() instead.Like this:

let numbering = document.querySelector("#numbering");
for (var i = 1; i <= 100; i++) {
  numbering.insertAdjacentHTML('beforeend', i.toString() + "<br>")
}
<div id="numbering"></div>

Note that I also added the line break tag (<br>) to put each number on a new line.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
1

I'm far from being an expert (and I'm not trying to start an argument here) but have read that concatenating strings in a loop using += is not a good idea; for, since strings are immutable data types, more RAM is used. Also, I've read that you don't want to update the DOM multiple times in a loop either. It is recommended to use a document fragment, update it in the loop, and append it to the DOM once. Also, <br> tags aren't the most useful tag and you may want to place your numbers inside tag. That would also allow you to place a class on them for styling in CSS. You could place the class on the parent rather than one each child div tag; but I added this way just to illustrate it for you.

This is just and example to illustrate the point. These are only suggestions and pointers for when you do more, the other answers get you want you need quickly.

let numbering = document.querySelector("#numbering");

let frag = document.createDocumentFragment();
for (var e, i = 1; i <= 100; i++) {
  e = document.createElement('DIV');
  e.textContent = i;
  e.classList.add('blue','number');
  frag.appendChild(e);
}

numbering.append(frag);
#numbering {
 width: 50px;
}
div.number.blue {
  color: blue;
  font-family: Arial;
  text-align: right;
}
<div id="numbering"></div>
Gary
  • 2,393
  • 12
  • 31
0
let numbering = document.querySelector("#numbering");
for (var i = 1; i <= 100; i++) {
  numbering.innerHTML = numbering.innerHTML + i.toString();;
}
Ajay Gupta
  • 703
  • 5
  • 11