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

298
Views
Why is document.getElementById() returing null when ran through a for loop?

EDIT: I fixed it!

Turns out toString() is pretty useless since JS can turn numbers into strings implicitly and that was the problem, because when I removed it, it worked flawlessly!

document.getElementById("g").onload = function () { // #g is the body
    for (let i = 0; i < $h; i++) { // $h = 2
        for (let j = 0; j < $w; j++) { // $w = 5
            let l = String.fromCharCode(97 + i);
            document.getElementById(l+(j+1)).onclick = $add; // toString() sucks balls
        }
    }
};

THE ORIGINAL BRAIN-DAMAGE:

I'm developing a web-based game and I've discovered a problem with this code:

document.getElementById("g").onload = function () { // #g is the body
    for (let i = 0; i < $h; i++) { // $h = 2
        for (let j = 0; j < $w; j++) { // $w = 5
            let l = String.fromCharCode(97 + i);
            document.getElementById(l+toString(j+1)).onclick = $add;
        }
    }
};

Basically, the code is supposed to run through elements with an ID of a1,a2...a5,b1,b2...b5 and assign the void $add to onclick of each element. For some very strange reason, it's giving me this error:

Uncaught TypeError: can't access property "onclick", document.getElementById(...) is null

I've tried so many things that I can't even list them here without it looking like a 2-year-old toddler who has the mental capacity of a half-eaten blackberry wrote it.

I am like the yogurt that's been sitting in my fridge for about 2 months at this language.

Also, to inflict extra damage to my protein-shake-brain, the script in the HTML is defined after the stuff in my code.

about 4 years ago · Juan Pablo Isaza
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!