Reputation: 23
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);
}
Upvotes: 1
Views: 157
Reputation: 11080
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.
Upvotes: 1
Reputation: 2871
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>
Upvotes: 1
Reputation: 841
let numbering = document.querySelector("#numbering");
for (var i = 1; i <= 100; i++) {
numbering.innerHTML = numbering.innerHTML + i.toString();;
}
Upvotes: 0