jll1989
jll1989

Reputation: 13

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);
}

Upvotes: 0

Views: 294

Answers (1)

Firegifguy
Firegifguy

Reputation: 51

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.

Upvotes: 1

Related Questions