The reason why your solution does not work is you are selecting all the number elements on each iteration. $(".number").append(...) So on every loop you select al the elements and you append to them. That is why the numbers are added to each one.
You should be selecting the index you are on....
var numbers = $('.number') // select all the numbers
for (let num = 0; num < list; num++) { // loop
numbers.eq(i).text(num); // set the text of the current index
}
It would be better just use text() with a function if you want to go the jQuery way
$('.number').text(function(index) {
return (index + 1);
});
Now your other options:
Best option, have whatever spits out the HTML generate it....
Next option, You could just use an ordered list and you would get the numbers.
Another option, you do not need JavaScript, pure CSS can insert the number
ol {
margin :0;
padding:0;
counter-reset:li;
list-style: none;
}
ol li:before {
content:counter(li);
counter-increment:li;
font-weight: bold;
padding-right: .5em;
}
<ol>
<li>Apple</li>
<li>Pear</li>
<li>Bacon</li>
</ol>
or if you really want JavaScript
document.querySelectorAll("#myList li").forEach(function(li, i) {
li.innerHTML = '<span>' + (i + 1) + '</span>' + li.innerHTML
})
ol {
margin: 0;
padding: 0;
counter-reset: li;
list-style: none;
}
ol li span {
font-weight: bold;
padding-right: .5em;
}
<ol id="myList">
<li>Apple</li>
<li>Pear</li>
<li>Bacon</li>
</ol>
if the spans exist, than just change the text
document.querySelectorAll("#myList li span").forEach(function(span, i) {
span.innerHTML = (i + 1)
})
ol {
margin: 0;
padding: 0;
counter-reset: li;
list-style: none;
}
ol li span {
font-weight: bold;
padding-right: .5em;
}
<ol id="myList">
<li><span></span>Apple</li>
<li><span></span>Pear</li>
<li><span></span>Bacon</li>
</ol>