Search code examples
javascripthtmlnodes

How do I remove an image after adding it though JavaScript?


I'm working on a whack-a-mole game, and to create a mole in a hole, i needed an image. I found that image and inserted the image using JavaScript. The following code, I did it in an another file where i was trying to see which thing will work:

<div class="hole" id="h1"></div>
<script>
  let mole = `<img src="mole.jpg" height="70px" width="70px" class="mole">`;
  let moleNode = document.querySelector('.mole');
  document.querySelector('#h1').innerHTML = mole;
  document.querySelector('#h1').removeChild(moleNode); // Error: moleNode is not of type node.
  // I also tried:
  mole.parentNode.removeChild(moleNode); // Same thing as above. Also I thought it wouldn't work because there were 36 holes and I don't actually know how to do it then.
</script>

Solution

  • The problem is you're trying to remove the moleNode before it has been added to the DOM. You need to swap the two lines to get it fixed. Also, in the code one more suggestion is it's not a good idea to name the id with standard HTML element(h1 in your case) so I changed it.

    let mole = `<img src="mole.jpg" height="70px" width="70px" class="mole">`;
    document.querySelector('#specific-id').innerHTML = mole; // Swapped with below
    
    let moleNode = document.querySelector('.mole'); // Swapped with above
    
    // Remove the moleNode when needed
    moleNode.parentNode.removeChild(moleNode);
    // or document.querySelector('#specific-id').removeChild(moleNode);
    <div class="hole" id="specific-id"></div>