What removeChild() actually removes

·

3 min read

I recently watched Ania Kubów's video on building Chrome's Dino Game. I coded along, then decided to add some bits myself. Since I was looking at it a lot and refreshing it a lot I added a button to start the game and also play again without having to refresh it.

In the video the code uses removeChild() to remove the dinosaur and cacti when the game is over. It was after I died, then pressed Play that I discovered removeChild() doesn't quite do exactly what I think it does.

When I said that it removes the dinosaur and cacti from the game, I thought that it removed them completely and they'd need re-adding. I changed it so it only removed the obstacles, but for some reason it was acting like the obstacles were still there when I played again, even though I couldn't see them. There's an important line in the documentation that reveals what's going on:

The removed child node still exists in memory, but is no longer part of the DOM.

MDN Web Docs

removeChild() removes the cacti from the DOM. If you inspect the page, there are no cacti anywhere in the HTML. However, the cacti still exist, you just can't see them. After removing them, when I pressed play, they came back. Still invisible, but in the Inspector, they return.

There are ways in which you can use this. And if you have no references to the child after it's removed then JavaScript will delete it. But in summary, be careful. The node might still be there, you just can't see it.