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

128
Visualizações
can't access property "innerHTML", document.getElementById('id' +num) even though js is declared at the end of <body>

I'm trying to pick a random value for each row of the array in js, however when i run the code i get Uncaught TypeError: can't access property "innerHTML", document.getElementById(...) is null even though the script is at the bottom of

 <p id="crit1"></p>
            <p id="crit2"></p>
            <p id="crit3"></p>
            <p id="crit4"></p>
            <p id="crit5"></p>

        <script>
        

            var criteria = [
              ['opt1', 'opt2'], 
              ['opt3', 'opt4'],
              ['opt5', 'opt6'], 
              ['opt7', 'opt8'], 
              ['opt9', 'opt10']
            ];

            for (var step = 0; step <5; step++){
                var rand = Math.round(Math.random()); //genrates either 0 or 1
                if (rand == 1) {
                    document.getElementById('crit'+ step).innerHTML = criteria[step][1];
                    var answ = answ +1;
                } else {
                    document.getElementById('crit'+ step).innerHTML = criteria[step][0];
                }
            }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It's failing because your step counter starts at 0 but you have no element with ID crit0.

If you add a crit0 element or start your counter at 1, the error goes away.

It can also be helpful to also include a null check for document.getElementByID() to avoid throwing errors when it can't find the element:

const critElement = document.getElementById('crit' + step);
if (critElement) {
    critElement.innerHTML = criteria[step][0];
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The step is start from 0. So, the first iteration will find the element with id=crit0. There is no id with that name. You can change the start iteration from 1 instead.

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