How can I load the length (li index-1
) of li
into each li
instead of X
?
var element = document.getElementById("ul");
var numberOfChildren = element.getElementsByTagName('*').length
//document.write(numberOfChildren) ;
for (let x = 0; x < numberOfChildren; x++) {
let newCount = x + 1;
document.getElementsByTagName("li").innerHTML = newCount;
console.log("li = " + newCount);
}
<ul id="ul">
<li>X</li>
<li>X</li>
<li>X</li>
<li>X</li>
<li>X</li>
<li>X</li>
</ul>
3
Answers
You can do this by setting the
innerHTML
of eachli
rather than the group of all list elements. A working version of your code is below:As I understand your question, you can use
querySelectorAll
with li and iterate withforEach
:Two possible approaches are below, with explanatory comments in the JavaScript to explain what’s happening:
References:
Array.prototype.forEach()
.document.getElementById()
.document.querySelectorAll()
.Element.children
.