First, take a look at this answer why you shouldn't be using document.write
.
Then, after you understand why using document.write is bad practice, you can replace it with element.appendChild
.
For more information about the function, visit the Mozilla Development Network.
Code example:
var numOfDice = prompt("How many dice?");
var numOfSides = prompt("How many sides on these dice?");
var rollDice = function(numOfDice) {
var rollResults = [];
for (var i = 0; i < numOfDice; i++) {
rollResults[i] = Math.floor((Math.random() * numOfSides) + 1);
}
return rollResults;
}
var printResults = function() {
var i = 0;
while (i < rollResults.length - 1) {
var node = document.createElement("p");
node.innerHTML = rollResults[i] + ", ";
document.querySelector("body").appendChild(node);
i++;
}
var node = document.createElement("p");
node.innerHTML = rollResults[i];
document.querySelector("body").appendChild(node);
}
alert("Roll the dice!");
var rollResults = rollDice(numOfDice);
printResults();
setTimeout(function() {
var node = document.createElement("p");
node.innerHTML = "These numbers...";
document.querySelector("body").appendChild(node);
}, 1000);
Note that this code will show each rolled dice on a new line, since I'm creating a new p element for every roll. If you want them to appear on the same line, create one p element, and then in the while loop, append the rollresult to that p elements `innerHTML´ .