views:

135

answers:

5

How to remove HTML <body> element with all of its content?

var e = document.getElementsByTag('html');
e.removeChild('body');

Does not work.

+4  A: 

The simple solution would be

 document.body.innerHTML = "";

But why on earth would you want to do this?

By the way:

 var e = document.getElementsByTag('html');

should be

 var e = document.getElementsByTagName('html')[0];

and

 e.removeChild('body');

should be

 e.removeChild(document.body);
Sean Kinsey
hmm clear a mess, then put more in?
Mark Schultheiss
And by that you mean?
Sean Kinsey
"But why on earth would you want to do this?" suppose you wanted to just start over inserting stuff (new body...)
Mark Schultheiss
Thats pretty much a given, but I would guess that clearing the body is really only a symptom of bad design (code that is)
Sean Kinsey
+5  A: 
  1. getElementsByTagName returns a collection of nodes, not a single node
  2. removeChild takes a node, not a string containing a tag name
    var e = document.body;
    e.parentNode.removeChild(e);

… however HTML documents require a body element, so this may have unexpected behavior.

David Dorward
actually, chrome will allow it.
Sean Kinsey
By the way, I'm guessing you mean 'getElementsByTagName **returns** a ..'
Sean Kinsey
Chrome will allow what? You to remove the body element? Great. So that's one browser out of … lots (present and future). Corrected the typo.
David Dorward
Actually, any browser will allow removing the body element. That doesn't make it a good idea.
Ms2ger
+1  A: 

I think this will remove it

var html = document.getElementByTagName('html')[0];
var body = document.getElementByTagName('body')[0];
html.removeChild(body);
Nort
this might mess up your global namepsace, btw..., probably need a `var` in here.
Dan Beam
true, true :) thanks for the advice
Nort
A: 

document.body.parentNode.removeChild(document.body)
or
document.body = document.createElement("body")
or
while(document.body.childNodes.length != 0) document.body.removeChild(document.body.childNodes[0])

ItzWarty
+1  A: 

...

document.body.parentNode.removeChild(document.body);
Web Logic