title: Cannot read property 'setAttribute' of null - Javascript
body: <p>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?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var dice = [6, 6, 6, 6, 6];
  
  function rollDice() {
    for (var i = 0; i &lt; dice.length; ++i) {
      var num = Math.floor(Math.random() * 6 + 1);
      dice[i] = 1;
      document.write(dice[i] + "&lt;br&gt;");
    }
    for (var i = 0; i &lt; 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)
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt;
  
  &lt;head&gt;
  
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Project 1&lt;/title&gt;
    &lt;link rel="stylesheet" type="text/css" href="css/style.css"&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
    &lt;h1&gt; This is a javascript application&lt;/h1&gt;
    &lt;script&gt;
      console.log("script #1: %o", document.getElementById("dice_1")); // null
    &lt;/script&gt;
    &lt;div&gt;
      &lt;img id="dice_1" src="images/dice 1.png"&gt;
      &lt;img id="dice_2" src="images/dice 1.png"&gt;
      &lt;img id="dice_3" src="images/dice 1.png"&gt;
      &lt;img id="dice_4" src="images/dice 1.png"&gt;
      &lt;img id="dice_5" src="images/dice 1.png"&gt;
    &lt;/div&gt;
    &lt;input id="but" type="button" onclick="rollDice()" value="Roll Dice."&gt;
    &lt;script&gt;
      console.log("script #1: %o", document.getElementById("dice_1")); // null
    &lt;/script&gt;
    &lt;script type="text/javascript" src="scripts/script.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
  
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>