Hi, This is the first time i am on this forum and hope someone can help. I have created a 2 player Dice game. The idea is that each player in turn rolls the dice. This is a 6 sided each, 2 dice per player. After each roll the numbers need to be added. I am trying to extract numbers and then total these numbers using javascript. so far i have a <div id="score">5,2,10,13</div> The numbers within the div i need it to total e.g 30 Many Thanks Vinny
Something like this should work: var numbers = document.getElementById('score').innerHTML.split(","); var sum = 0; for (var i = 0; i < numbers.length; i++) { sum += parseInt(numbers[i]); } console.log(sum); Code (JavaScript):
I am getting the following response 'NaN' to your code. This is my code: var myScore = document.getElementById("score"); var die3 = document.getElementById("die3"); var die4 = document.getElementById("die4"); var d3 = Math.floor(Math.random()*5)+1; var d4 = Math.floor(Math.random()*5)+1; var Total = d3 + d4; die3.innerHTML = d3; die4.innerHTML = d4; var score=0; let sum = Total.reduce((Total, val)=>{ return Total + val;},0); myScore.innerHTML +=""+sum+","; Code (markup): I get the following output <div id='score'> 12,10,9,1,2</div> I tried using innerText which strips the div tag and gives me 12,10,9,1,2 which works but I want a total of these numbers?