0

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.

BSMP
  • 4,596
  • 8
  • 33
  • 44
Leandro Zhuzhi
  • 304
  • 1
  • 7
  • 17

4 Answers4

9

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);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Or you can do `document.getElementById("marginDiv").remove()` – Raynos May 03 '12 at 14:33
  • Since chrome 19 I think. It's in DOM4 – Raynos May 03 '12 at 14:33
  • Both functions are children of body because that's where i create them, using this code: var marginDiv = document.createElement("div"); marginDiv.setAttribute("id", "marginDiv"); docBody.appendChild(marginDiv); The code is working in another script, for example when you click twice on a button, the thumbnail list gets deleted and created again. Before i used this code to delete it, it used to create a new list whenever i clicked a button. If im doing it wrong, shouldn't it not work at all? sry for messed up code, i dont know how to write it cleanly – Leandro Zhuzhi May 03 '12 at 14:41
5

Try

docBody.removeChild(document.getElementById("marginDiv"));
Amberlamps
  • 39,180
  • 5
  • 43
  • 53
1

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);
}
Andrew Leach
  • 12,945
  • 1
  • 40
  • 47
jenswirf
  • 7,087
  • 11
  • 45
  • 65
0
if(document.getElementById("marginDiv")){
  docBody.removeChild("marginDiv");
}

you have to check if specified element exist marginDiv exist, then removechild(...)

devzom
  • 676
  • 1
  • 9
  • 19