'use .length to define the end of a loop

When trying to work with loops in javascript I'm facing an error saying: TypeError: Cannot read properties of undefined (reading 'innerText')

I guess the problem is related to how I define the end of the loop using .length

This is the code I'm trying:

let els = document.getElementsByClassName('myClass');
for(var i = 0; i < els.length; i++)
{
    els = document.getElementsByClassName('myClass')[i].innerText
    console.log(els);
}

Trying to debug it, I looked for the exact length and format of els.length and the result is:

format=number value=6

If I change the end of the loop (see below) I don't get that error anymore:

let els = document.getElementsByClassName('myClass');
for(var i = 0; i < 6; i++)
{
    els = document.getElementsByClassName('myClass')[i].innerText
    console.log(els);
}


Solution 1:[1]

You used the els twice. At the end of each loop, it checks if i < els.length but you have made els a string so els.length is different.

You should name the second els differently.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Firegifguy