Reputation: 13
I have seen a couple of questions posted with this error on here and having seen some of the answers I noticed the general consensus is that it is caused due to the DOM not being created yet. I have tried a few different solutions to fix it such as moving my script to immediately prior to the tag, using log outputs before and after the image creation in order to ensure the object is actually being created correctly but nothing has resolved my issue. I am new to Javascript so it might be something obvious I am missing?
var dice = [6, 6, 6, 6, 6];
function rollDice() {
for (var i = 0; i < dice.length; ++i) {
var num = Math.floor(Math.random() * 6 + 1);
dice[i] = 1;
document.write(dice[i] + "<br>");
}
for (var i = 0; i < dice.length; ++i) {
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value];
}
document.getElementById("dice_1").setAttribute("src", path)
}
<html>
<head>
<meta charset="utf-8">
<title>Project 1</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1> This is a javascript application</h1>
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<div>
<img id="dice_1" src="images/dice 1.png">
<img id="dice_2" src="images/dice 1.png">
<img id="dice_3" src="images/dice 1.png">
<img id="dice_4" src="images/dice 1.png">
<img id="dice_5" src="images/dice 1.png">
</div>
<input id="but" type="button" onclick="rollDice()" value="Roll Dice.">
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<script type="text/javascript" src="scripts/script.js"></script>
</body>
</html>
Upvotes: 1
Views: 12232
Reputation: 312
Since you're using document.write after the document has loaded, it's clearing the entire document (due to document.open() being called). Therefore, your img elements do not exist for setAttribute to be run against them. Try the following (note the index corrections that are needed due to array indexing starting at zero):
var dice = [6,6,6,6,6];
var results;
var resultsContainer = document.querySelector('.results');
function rollDice(){
// clear results array
results = [];
for(var i =0; i<dice.length; ++i){
var num = Math.floor(Math.random()*6 +1);
dice[i] = num;
results.push(dice[i]);
}
for(var i =0; i< dice.length; ++i){
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3.png", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value - 1];
document.getElementById("dice_"+ (i + 1)).setAttribute("src",path);
}
// convert results array to text with <br> between them
var resultsStr = results.join("<br>");
// display results as text to page
resultsContainer.innerHTML = resultsStr;
}
Upvotes: 1