How to delete an image you have append?

Viewed 34

I am new at JavaScript and want to know how to delete an image that you have append?

The error message is: TypeError: document.getElementById(...) is null

let myCars = new Array();
let positionTop = 100;


function addCar(){
    var img = document.createElement("img");
    img.src = "/res/Car.png";

    img.style.position = "absolute";
    img.style.top = positionTop + "px";
    img.style.left = "25px";
    positionTop += 100;

    myCars.push(img);

    document.getElementById("car").appendChild(img);
}


function deleteCar(){
    document.getElementById(myCars[myCars.length - 1]).remove; // TypeError
    myCars.splice(myCars.length - 1, 1);
}
2 Answers

You already pushed the whole image element inside the myCars array.

So, you can directly remove the image from it as it has the reference of the image.

function deleteCar(){
    myCars[myCars.length - 1].remove();
    myCars.splice(myCars.length - 1, 1);
}

Your image does not have an id so you can select the image directly and delete it.

document.getElementById(myCars[myCars.length - 1]) is an invalid syntax because myCars is a list of DOM elements. If you access myCars[index] it will return a DOM element so document.getElementById(myCars[myCars.length - 1]) will be an invalid syntax. Since myCars[myCars.length - 1] already return a DOM element, you can simpley call remove() on the same node, just like myCars[myCars.length - 1].remove();

let myCars = new Array();
let positionTop = 100;

function addCar() {
  var img = document.createElement("img");
  img.src = "/res/Car.png";
  img.style.position = "absolute";
  img.style.top = positionTop + "px";
  img.style.left = "25px";
  positionTop += 100;

  myCars.push(img);

  document.getElementById("car").appendChild(img);
}

function deleteCar() {
  myCars[myCars.length - 1].remove();
  myCars.splice(myCars.length - 1, 1);
}
<div id="car"></div>
<button onclick="addCar()">Add Car</button>
<button onclick="deleteCar()">Delete Car</button>

Related