Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: document.getElementById(...)[0] is undefined

Tags:

javascript

Ok, guys. I'm not sure why this doesn't work. Following an example the teacher gave us and as far as I can tell, everything is the same except for the function and variable names... Using an external JavaScript file, Dreamweaver says there's no syntax errors or anything else of the sort but debugger on Firefox says TypeError: document.getElementById(...)[0] is undefined... which I'm not exactly sure why but here is my code:

JavaScript:

var caveboyanim = new Array(6);
var curCaveBoy = 0;

for (var i = 0; i < 6; ++i) {
    caveboyanim[i] = new Image();

    caveboyanim[i].src = "images/caveboy" + i + ".png";
}

function caveboyanimation() {
    if (curCaveBoy == 5)
        curCaveBoy = 0;
    else ++curCaveBoy;
    document.getElementById("caveboy")[0].src = caveboyanim[curCaveBoy].src;
}

HTML:

<body onLoad="setInterval('caveboyanimation()', 1000);">

<img src="images/caveboy0.png" id="caveboy"  alt="Image of a cave boy">

</body>
like image 690
FunkyMonkey Avatar asked Nov 17 '25 22:11

FunkyMonkey


2 Answers

remove the [0] from:

document.getElementById("caveboy")[0].src = caveboyanim[curCaveBoy].src;

The index 0 is used with jQuery objects to get "real" document element. But you are not using JQuery here so it's not needed.

like image 178
Hardy Avatar answered Nov 20 '25 11:11

Hardy


The return of document.getElementById() is not an array. Use:

document.getElementById("caveboy")
like image 25
user13500 Avatar answered Nov 20 '25 12:11

user13500