kinezu
kinezu

Reputation: 1272

Having trouble trying to clear out an image previously created using Javascript

With a button click, I am adding an image to a div titled 'floatingButton1'. Later on, I want to run a separate function and remove the image I added so that the background image can be seen.

Here is my code to add the image.

var floatingButton1 = document.getElementById('floatingButton1');
    var i1 = document.createElement("img");
    i1.src = "Images/tnR1.png";
    i1.type = "image";
    floatingButton1.appendChild(i1);

I have tried to remove it like this but it does not work:

var floatingButton1 = document.getElementById('floatingButton1');
var i1 = document.createElement("img");
i1.src = "Images/whitesquare.png";
i1.type = "image";
floatingButton1.removeChild(i1);

How do I remove the image from the DIV / clear out all of the images I made.

Upvotes: 0

Views: 38

Answers (2)

Sarbbottam
Sarbbottam

Reputation: 5580

var floatingButton1 = document.getElementById('floatingButton1');
var i1 = document.createElement("img");
i1.src = "Images/whitesquare.png";
i1.type = "image";

The above code is not required in the second time. var i1 already holds the reference to the image appended.

Just use

floatingButton1.removeChild(i1);

Upvotes: 1

mechalynx
mechalynx

Reputation: 1302

When you run

var i1 = document.createElement("img");

the second time, it creates a new img tag. To remove it all you need is

floatingButton1.removeChild(i1);

with out any of the other code in your second code block. None of that is necessary and when you redefine i1 you've lost the reference entirely.

Upvotes: 1

Related Questions