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

299
Visualizações
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
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