Wongesse Wongesse - 11 months ago 37
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;

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){

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>


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

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);
    return imageId;

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

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

and later on...

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