It has nothing to do with your JavaScript. You have an empty, hard-coded <li>
element in your HTML. Remove it.
//VARIABLES
let list = document.querySelector('ul');
//PRINT NUMBERS 1 - 100 TO THE SCREEN
for(i = 1; i <= 100; i++){
let li = document.createElement('li');
li.innerHTML = [i];
list.appendChild(li);
}
<div class = "container_list">
<ul></ul>
</div>
Now, I realize you are just doing an exercise, but your solution introduces a common performance bug. Every time you update the web page content, the client has to "re-flow" all the content already on the page and "re-paint" the UI with that new content. This uses resources. The more you do it, the more resources it takes.
You are appending a new bullet to the ul
that is already on the page upon each iteration of the loop, so you are causing re-flows and re-paints 100 times with your code!
Instead, you should build the entire ul
in memory and then when it is fully constructed, you can append the whole thing just once, when the loop is finished.
Finally, .innerHTML
is for when you are getting/setting strings that contain HTML that needs to be parsed by the HTML parser. If your string doesn't contain any HTML, that's a waste (and under certain circumstances, a security risk). In those cases use .textContent
, which doesn't engage the HTML parser.
//VARIABLES
let list = document.querySelector('ul');
let ul = document.createElement("ul"); // This will hold all the list items
//PRINT NUMBERS 1 - 100 TO THE SCREEN
for(i = 1; i <= 100; i++){
let li = document.createElement('li');
li.textContent = [i]; // Use .textContent when the string doesn't contain any HTML
ul.appendChild(li);
}
// Now, append the entire list to the document with just one DOM change
document.querySelector(".container_list").appendChild(ul);
<div class = "container_list"></div>