Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Appending and Removing Elements

susan corbett
susan corbett
3,060 Points

don't understand how to get the parent node to use the "removeChild" method in the challenge exercise, returns exception

I don't understand how to select the correct parent node to use the "removeChild" method in the project exercise.

Every time I try, it returns an Exception error.

I thought the Body was the parent, and the paragraph to be removed is the child I should select, but it doesn't work!

Please help!

app.js
var body = document.body;
var newParagraph = document.createElement("p");
var pleaseEnableParagraph = document.querySelector("#please_enable");

//Remove "Please Enable JavaScript" paragraph

body.removeChild("pleaseEnableParagraph");

//Append new paragaph to document
index.html
<!DOCTYPE html>
<html>
  <body>
    <p id="please_enable">Please Enable JavaScript</p>

    <script src="app.js"></script>
  </body>
</html>

Using document.body is risky because the body may not always be the parent. Use this method below.

// Get the element you want to remove
var el = document.getElementById('foo');
// Get the elements parent
var elParent = el.parentNode;
// Remove the element
elParent.removeChild(el);

You could also turn this into a simple helper function like so

function removeElement(el) {
    el.parentElement.removeChild(el);
}

1 Answer

Alex Sell
Alex Sell
19,355 Points

You're removing a string, not the variable. Try

 body.removeChild(pleaseEnableParagraph) 
susan corbett
susan corbett
3,060 Points

Thank you so much! That's what it was! It was stressing me completely out! I needed to remove the quotation marks because they were making it a string instead of a variable! Thank you!!!!

Alex Sell
Alex Sell
19,355 Points

You're very welcome. Happy coding :)