I am trying to create a dice game that has two dice rolled and the sum found. The running total is also meant to be shown beside the dice. The problem, however, is that NaN is showing. Here is the code:
HTML (part related to the running total)
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<div id="runningTotal" class="total">0</div>
Javascript (part related to the running total)
const runningTotal = document.getElementById( 'runningTotal' );
const parsedTotal = parseInt(runningTotal);
runningTotal.innerHTML = parsedTotal + diceTotal;
Any ideas how to fix it?
You need to get the content of the runningTotal
element, and then convert that to an integer. getElementById
returns an element object, rather than its contents. This means that your code is trying to convert the element itself (the entire div
) to an integer, rather than convert the contents of the element (0) to an integer.
You can use innerText
to retrieve the contents of the element:
const runningTotal = document.getElementById( 'runningTotal' );
const parsedTotal = parseInt(runningTotal.innerText);
runningTotal.innerHTML = parsedTotal + diceTotal;