Remove an Element


Hello, I’m working on the remove an element lesson. I’m getting confused on when to use ‘document’ vs ‘document.body’ or when I even need to use them at all. Take for example the above lesson, here is the answer:

let child = document.getElementById('oaxaca')
let parent = document.getElementById('more-destinations')
document.removeChild(child)  //doesn't work
document.body.removeChild(child)  // doesn't work
parent.removeChild(child) // works

I read this post on stackoverflow which I understood as meaning that I don’t have to include ‘body’ because it limits the search for the element. Can someone please clear this up in my mind?

Thank you.


That is because child is not a direct child element of document or of body, but of #more-destinations.


Okay so I must use "a direct child element of document or of body"?

I decided to try a few things.

let child = document.getElementById('oaxaca')
//let parent = document.getElementById('more-destinations')
//document.body.getElementById('more-destinations').removeChild(child)  // DOES NOT WORK
document.getElementById('more-destinations').removeChild(child)  // DOES WORK

How come the document.body.... attempt above to removeChild doesn’t work? In index.html, I see all of the li elements inside the <body></body> tags.

I need to fix my thinking here because not understanding this is having a cascading impact on my ability to understand things in follow on lessons.

BTW: there are caching issues with this page. I need to remember to use CTRL-F5 to clear my cache else the index.html page in the 3rd window doesn’t reset even after clicking the reset icon.


P is a direct child of DIV, and DIV is direct child of BODY.

elementNode.removeChild(child) will only work on direct child.


thank you for your insight.