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:
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
The error:
SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference
scripts.js (54,2)
EDIT: updated entire function
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 <= rows; i++) {
var marquee = document.createElement("marquee");
marquee.setAttribute("scrollamount", 30);
for (var j = 1; j <= 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);
generateRandom function:
function generateRandom(n) {
return Math.floor((Math.random() * n) + 1);
}