Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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];
                }
            }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading