Javascript 移除 body 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2899649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove body element
提问by w00
How to remove HTML <body>element with all of its content?
如何删除 HTML<body>元素及其所有内容?
var e = document.getElementsByTag('html');
e.removeChild('body');
Does not work.
不起作用。
回答by Sean Kinsey
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);
回答by Quentin
- getElementsByTagName returns a collection of nodes, not a single node
- removeChild takes a node, not a string containing a tag name
- getElementsByTagName 返回节点集合,而不是单个节点
- removeChild 接受一个节点,而不是一个包含标签名称的字符串
var e = document.body;
e.parentNode.removeChild(e);
… however HTML documents requirea body element, so this may have unexpected behavior.
……然而 HTML 文档需要一个 body 元素,所以这可能会有意想不到的行为。
回答by w00
...
...
document.body.parentNode.removeChild(document.body);
回答by Max Ruf
I think this will remove it
我认为这将删除它
var html = document.getElementsByTagName('html')[0];
var body = document.getElementsByTagName('body')[0];
html.removeChild(body);
回答by Warty
document.body.parentNode.removeChild(document.body)
ordocument.body = document.createElement("body")
orwhile(document.body.childNodes.length != 0) document.body.removeChild(document.body.childNodes[0])
document.body.parentNode.removeChild(document.body)
或document.body = document.createElement("body")
或while(document.body.childNodes.length != 0) document.body.removeChild(document.body.childNodes[0])
回答by Martin Zeitler
the bodyitself has a method which does just that:
在body本身有其做到了这一点的方法:
document.body.remove();

