title: Unable to get property 'parentNode' of undefined or null reference
body: <p>My javascript program basically creates a series of images and randomly picks one and sets its src to a particular path. However, for some reason, the code seems to get stuck sometimes. In my program, I'm calling element.parentNode of one of the images in order to surround it with an anchor tag but it throws a console error saying that it is unable to get property 'parentNode' of undefined or null reference despite the fact that sometimes, the code actually executes sometimes without any changes to the code. I have to refresh multiple times before I get lucky enough to have the error not be thrown and the rest of the code executed smoothly.
  Here is my code:</p>
  
  <pre><code>var id = generateRandom(325);
  var el = document.getElementById(id.toString());
  var anchor = document.createElement("a");
  var nextPage = "level" + (level + 1).toString() + ".html";
  if (level == 3) {
      nextPage = "win.html";
  }
  anchor.setAttribute("href", nextPage);
  el.parentNode.insertBefore(anchor, el); // line 54
  </code></pre>
  
  <p>The error:</p>
  
  <pre><code>    SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference
  scripts.js (54,2)
  </code></pre>
  
  <p>EDIT:
  updated entire function</p>
  
  <pre><code>var div = document.getElementById("images");
  var time = parseInt(document.getElementsByClassName("timer")[0].innerHTML);
  var level = getLevel(time);
  var rows = 13;
  var cols = 23;
  for (var i = 1; i &lt;= rows; i++) {
      var marquee = document.createElement("marquee");
      marquee.setAttribute("scrollamount", 30);
              for (var j = 1; j &lt;= cols; j++) {
          var img = document.createElement("img");
          img.setAttribute("src", getPath());
          img.setAttribute("id", (i * j).toString());
          img.setAttribute("width", "80px");
          img.setAttribute("height", "70px");
          marquee.appendChild(img);
      }
      div.appendChild(marquee);
  }
  var id = generateRandom(rows * cols);
  var el = document.getElementById(id.toString());
  var anchor = document.createElement("a");
  var nextPage = "level" + (level + 1).toString() + ".html";
  if (level == 3) {
      nextPage = "win.html";
  }
  anchor.setAttribute("href", nextPage);
  el.parentNode.insertBefore(anchor, el);
  var input = document.createElement("input");
  input.setAttribute("type", "image");
  input.setAttribute("width", "80px");
  input.setAttribute("height", "70px");
  input.setAttribute("src", "resources\\asotigue.jpg");
  el.parentNode.replaceChild(input, el);
  anchor.appendChild(input);
  </code></pre>
  
  <p>generateRandom function:</p>
  
  <pre><code> function generateRandom(n) {
      return Math.floor((Math.random() * n) + 1);
  }
  </code></pre>