Question

I'm trying to get a very simple Javascript function to work that will change one image for another using .removeChild and .appendChild. My code is as follows:

<html> 
<head> 
<script type="text/javascript" language="javascript"> 
function bannerload(){

var banner = new Image();
banner.src = "IMG/banner.gif";

var loading = new Image();
loading.src = "IMG/loading.gif";

var bannerElement = document.getElementById("BANNER");

bannerElement.removeChild(banner);
bannerElement.appendChild(loading);
}
</script> 
</head> 

<body onload="bannerload()"> 
<div id="BANNER">
<img src="IMG/banner.gif" alt="Banner" />
</div> 
</body> 
</html>

However, it's not working. The page just loads up with banner.gif and this image is never changed to loading.gif. I can't figure out why, some help pls?!

Thanks!

Was it helpful?

Solution

The reason this doesn't work is you are trying to add a child and remove a child that isn't a child.

You are trying to remove the child named BANNER from the element named BANNER.

Obviously the element named BANNER doesn't have a child named banner. You have two choices either give the id to the child element and call `banner.parent.removeChild(banner) or the following:

Example snipet

var bannerElement = document.getElementById("BANNER");
//Banner only has one child.
var child = bannerElement.children[0];

bannerElement.removeChild(child);
bannerElement.appendChild(loading);

OTHER TIPS

I think your problem is that you're trying to remove a child that doesn't exist in the bannerElement.

var banner = new Image();
banner.src = "IMG/banner.gif";
...
bannerElement.removeChild(banner);

See how you're making a new image and then removing it, even though you didn't append it yet? I think you should try something like this:

var banner = document.getElementById('id_banner')
banner.src = 'IMG/banner.gif' // or 'IMG/loading.gif' depending on which one you want
...
<body onload="bannerload()"> 
    <div id="BANNER">
        <img id="id_banner" src="IMG/banner.gif" alt="Banner" />
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top