Home > front end >  can't access property "innerHTML", document.getElementById('id' num) even
can't access property "innerHTML", document.getElementById('id' num) even

Time:07-03

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related