Javascript removeChild Not Working

Javascript removeChild Not Working

I am using this JavaScript code to remove a couple elements from the page, but it's not working. When I inspect the code with Opera Dragonfly it says something like:

Uncaught exception: Error: WRONG_ARGUMENTS_ERR

and points to the file and function name.

The weird thing is that I use the exact same code in another function on the same page and it works without problem. The code is very small and simple:

var docBody = document.getElementById("body");
if(document.getElementById("marginDiv")){
  docBody.removeChild("marginDiv");
}

Both body and marginDiv exist on the page. My goal is to make the thumbnails disappear when one clicks the background.

3 Answers

You're trying to remove a string. A string is hardly an HTML element. You're also relying on marginDiv being a direct child of body, which may not be the case.

Instead, try this:

var remove = document.getElementById('marginDiv');
if( remove) remove.parentNode.removeChild(remove);
3

Try

docBody.removeChild(document.getElementById("marginDiv"));
3

removeChild needs a reference to a DOM element, not a string. Try this:

var docBody = document.getElementById("body");
var marginDiv = document.getElementById("marginDiv");

if(marginDiv)){
docBody.removeChild(marginDiv);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.