1

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 ?

4 Answers 4

5
var img = document.createElement("IMG");
img.src = "images/1.gif";
var oldImg = document.getElementById('oldImg');
document.getElementById('imgDiv').replaceChild(img, oldImg);
Sign up to request clarification or add additional context in comments.

1 Comment

exactly same posted by me... u posted first so i m deleting mine :-)
3
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); 

2 Comments

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..
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.
1

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]);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.