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

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

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 Report

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 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!