Question

I'm using removeChild to delete an appendChild image, removeChild is triggered by an onclick event.

Elaboration:

USER clicks a button and appends an image next...

Code:

var src = "img2/" + selected + ".jpg";
      var img = document.createElement("img");
      img.src = src;
      img.id = 'someImage';

     if ($('#someImage').length === 0){ 
            holder.appendChild(img);
      img.style.display = "inline";
            display =  true;
            console.log(display);
            console.log(country);
            console.log(selected);

User Clicks Remove Button to remove the append Image

Code:

selected =  document.getElementById("country").value;
  display = false;
  document.getElementById("country").value = "";
  selected = null;    
  var Myholder = document.getElementById("holder");
  Myholder.removeChild(Myholder.childNodes[0]);

The code works properly however while cleaning up my code I saw an error in the console that says "TypeError: Argument 1 of Node.removeChild is not an object." meaning the removeChild function is still working even if the appendChild is already removed. How can I limit/stop it when there is nothing to remove?(all the functions are triggered once the user clicks the button meaning when the user clicks the remove button when there is nothing to remove the error shows)

Was it helpful?

Solution

just check if the parent node has child nodes. if yes, invoke the action. else not

var Myholder = document.getElementById("holder");
if(Myholder.hasChildNodes()) {
    Myholder.removeChild(Myholder.childNodes[0]);
}

documentation : Node.hasChildNodes()

OTHER TIPS

Unless the image is always at position 0, you could also use querySelector to specifically find an img tag, check if the query returned an element and if it doesn, remove it. This code is slightly more robust to future changes, such as adding other children to holder (unless they also are images).

var holder = document.getElementById('holder'),
    img = holder.querySelector('img');

if (img) holder.removeChild(img);

Now, I noticed you were using jQuery, so you can also do:

$('#holder').find('img').remove();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top