Wongesse Wongesse - 5 months ago 10
HTML Question

How to append and remove images in a div (javascript and html)

I'm trying to make a function (in javascript) that removes an image I attached to a div in html, I am having trouble getting the image I want to remove. The overall idea is to be able dynamically attach and remove images w/o having to use multiple divs.
Here is the function to append the image

function appendImage(imageSource, Id){
var img = document.createElement("IMG");
img.src = imageSource;
document.getElementById(Id).appendChild(img);
}


The reason I create img in the function (instead of outside) is so that I can attach multiple new ones to the div, if I don't it just replaces the image
Here is what I'm trying to for the removing the image

function removeImage(imageSource,Id){
document.getElementById(Id).removeChild(img);
}


I cannot access img in the removeImage because it isn't in the scope. So is there a way to pass img into removeImage w/o making it global or maybe another completely different way not using append or remove?

I don't know if you need it but all i have in my html file is

<div id="image"></div>

Answer

Edit - added Codepen example:

click for Codepen example

To use removeChild(), it must be called from the parent of the node you are trying to remove. Your function would look something like this:

function removeImage(id) {
    var elementToBeRemoved = document.getElementById(id);
    elementToBeRemoved.parentNode.removeChild(elementToBeRemoved);
}

At its simplest, you could just require one parameter - the id of the desired element - and from that you can determine its parent node and remove it.

Edit for alternative:

Another thing you could try is have appendImage return something to reference later - either an id that you pass in, or a random number. This can be appended to the new img element, and you can reference that to remove it in the future.

function appendImage(imageSource, containerId, imageId) {
    var img = document.createElement("IMG");
    img.src = imageSource;
    img.setAttribute('id', imageId);
    document.getElementById(containerId).appendChild(img);
    return imageId;
}

function removeImage(imageId) {
    var elementToBeRemoved = document.getElementById(imageId);
    elementToBeRemoved.parentNode.removeChild(elementToBeRemoved);
}

var myImage = appendImage('my.jpg', 'image', 'testId123');

and later on...

removeImage(myImage); or removeImage('testId123');

Comments