I'm new to javascript and programming in general. I've put together my first browser game and while everything functions, I keep getting this pesky error in the console that says, "NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node" in my hover function.
function hover(myid) {
var id = myid;
var index = id[5];
document.getElementById(id).removeChild(GAME.mound[index]);
document.getElementById(id).appendChild(GAME.hover[index]);
GAME.sound[0].play();
}
Both GAME.mound and GAME.hover are arrays that store images. The thing I can't figure out is that I have a function that is nearly identical to reverse the image switch caused by the hover function, but it doesn't throw the error.
function out(myid) {
var id = myid;
var index = id[5];
document.getElementById(id).removeChild(GAME.hover[index]);
document.getElementById(id).appendChild(GAME.mound[index]);
}
Here is a line from the HTML that calls the functions:
<div id="drift0" class="snowdrift" onmouseover = "hover(this.id)" onmouseout = "out(this.id)" onclick = "popup(this.id)"></div>
Any help in this is greatly appreciated. Let me know if I didn't provide all the information needed to answer the question.
Thanks!
It seems you need to handle this exception, so do that. There doesn't seem to be any point to copying myid, it's a string and even if you modify it, the original isn't changed. You should pass a reference to the element to the listener rather than the ID, as it saves using getElementById twice.
Also, as Deryck suggested, replaceChild will do the change in one step:
function hover(myid) {
var el = document.getElementById(myid);
var index = myid[5];
if (GAME.mound[index].parentNode === el) {
// Replace mound image with hover image
e.replaceChild(GAME.hover[index], GAME.mound[index]);
}
GAME.sound[0].play();
}
If you pass this to the function rather than this.id, you could do:
function hover(el) {
var index = el.id[5];
if (GAME.mound[index].parentNode === el) {
e.replaceChild(GAME.hover[index], GAME.mound[index]);
}
GAME.sound[0].play();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments