V
V
Valentin Popov2018-03-17 07:12:30
JavaScript
Valentin Popov, 2018-03-17 07:12:30

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>

I'm planning to replace the text of elements with class 'one' with their ordinal number.
I can do it through a for loop like this:
function btnClick(){
  let elems = document.getElementsByClassName('www');
  
  for(let i = 0; i < elems.length; i++){
    elems[i].textContent = i+1;
  }
 
}

And how also to simply replace the text of an element with their ordinal number through a for of loop? Is it possible?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-05-25
@elarkov

Object.entries + destructuring:

for (const [ index, el ] of Object.entries(elems)) {
  ...

You just need to keep in mind that index will be a string. Or you can use querySelectorAll instead of getElementsByClassName to get the elements, which returns a NodeList that has its own entries method, and there the index will be a number:
const elems = document.querySelectorAll('.one');
for (const [ index, el ] of elems.entries()) {
  ...

L
Lumore, 2018-03-17
@Lumore

elems.map((item, index) => {
  item.textContent = index
})

==============================
elems.forEach(function(val, index) {
  elems[index].textContent = index;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question