Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda