Search code examples
javascriptdominnerhtmlconsole.log

An error due to adding .innerHTML to an element and attempting console.log


I am starting to learn JavaScript and am constructing a rock, paper, scissors game with DOM manipulation.

So far I am trying to link HTML buttons to the player choices:

<div class="choices">
<button id="rock">Rock</button>
<button id="paper">Paper</button>
<button id="scissors">Scissors</button>
</div>

I am then using Javascript to try and capture the value of the buttons to use within the game function:

JavaScript

<script>
const el = document.getElementsByTagName('button');
for (let i = 0; i <= el.length; i++) {
  console.log(el[i].innerHTML);
}

However, the above code delivers the following result in the console:

Rock
Paper
Scissors
Uncaught TypeError: Cannot read property 'innerHTML' of undefined at 
ui_rps.html:38

So the array is returned, but there is an error? Can someone please help and explain why this is and how I can remove it?


Solution

  • You need to change your for loop to from i <= el.length to i < el.length. At the moment, it's iterating to one more item than you have.

    For example, if you've got three items, then i will end up being 0, 1, 2, 3 – when you try and call el[3].innerHTML = 'blah' it won't work as el[3] is undefined.

    Hope that makes some sense!