Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!