tags:

views:

43

answers:

4

I want to show different images in a DIV, the turn of an image depend on a random number. The image name is like 1.gif, 2.gif, .. 6.gif

to do that I coded

var img = document.createElement("IMG");
img.src = "images/1.gif";
document.getElementById('imgDiv').appendChild(img);

but it does not replace the old image how ever it add an another image right in the bottom of first image.

syntax for DIV is:

<div id="imgDiv" style="width:85px; height:100px; margin:0px 10px 10px 375px;"></div>

may u halp me ?

A: 

If you want to replace an element, you need to use replaceChild, not appendChild.

David Dorward
+1  A: 
var dv = document.getElementById('imgDiv');

// remove all child nodes
while (dv.hasChildNodes()) { 
    dv.removeChild(dv.lastChild); 
} 

var img = document.createElement("IMG"); 
img.src = "images/hangman_0.gif"; 
dv.appendChild(img); 
Paul Kearney - pk
Great buddy,it work perfects.Please may u solve my old one problem described in my Question:Display label character by character using javascript?I will be thankful to you..
Muhammad Sajid
This will work (as long as the div has no other children that you don't want deleted), but on some machines you'll see a flicker as the old image is removed and the new one added that won't occur if you use .replace instead.
kekekela
A: 
var img = document.createElement("IMG");
img.src = "images/1.gif";
var oldImg = document.getElementById('oldImg');
document.getElementById('imgDiv').replaceChild(img, oldImg);
kekekela
exactly same posted by me... u posted first so i m deleting mine :-)
piemesons
A: 

I would not recommend changing the src of the element in question. That would cause a lag in the display of the next image while the browser downloads the next image. If you have a set number of images you would want to preload them the way you are doing so now.

If you have the following code:

 <div id="imgDiv" style="width:85px; height:100px; margin:0px 10px 10px 375px;"></div>

You can do this:

<script type="text/javascript>
     var nextImage = document.createElement("img");
     nextImage.src = "your source here";

     document.getElementById("imgDiv").appendChild(nextImage);
</script>

Now that you have an image in place you can use the replaceChild() method:

var imageDiv = document.getElementById("imgDiv");
imageDiv.replaceChild(nextImage, imageDiv.childNodes[0]);
John