Answer the question
In order to leave comments, you need to log in
How to get the index number of an element through a for of loop?
Is it possible to simply display the ordinal number of the elements through the for of loop. For example, I have an HTML structure:
<h2 class="one">Какой-то заголовок</h2>
<p class="one">Какой-то текст</p>
<p class="one">Какой-то текст</p>
<button id="btn" onclick="btnClick()">Нажми на меня!</button>
function btnClick(){
let elems = document.getElementsByClassName('www');
for(let i = 0; i < elems.length; i++){
elems[i].textContent = i+1;
}
}
Answer the question
In order to leave comments, you need to log in
Object.entries + destructuring:
for (const [ index, el ] of Object.entries(elems)) {
...
const elems = document.querySelectorAll('.one');
for (const [ index, el ] of elems.entries()) {
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question