Javascript 清除 DOM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6798100/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:54:10  来源:igfitidea点击:

Javascript Clear DOM

javascripthtmldom

提问by Peter Olson

I am wanting to completely clear the DOM with Javascript.

我想用 Javascript 完全清除 DOM。

I have tried a few things, like this:

我已经尝试了一些事情,像这样:

document.getElementsByTagName("html")[0].innerHTML = "";
document.body.innerHTML = "";

Interestingly, clearing the head like this will generate an error ("invalid target element for this operation") in IE, but will successfully clear the head in Chrome. However, clearing the body like this works in IE but fails silently in Chrome.

有趣的是,像这样清除头部会在 IE 中产生错误(“此操作的目标元素无效”),但会在 Chrome 中成功清除头部。但是,像这样清除主体在 IE 中有效,但在 Chrome 中无声无息地失败。

I have also tried

我也试过

document.childNodes.length = 0;

but this is apparently a read-only property and won't do anything.

但这显然是一个只读属性,不会做任何事情。

Is there a good cross-browser way to clear the DOM?

有没有一种好的跨浏览器方式来清除 DOM?

回答by alex

This works...

这工作...

document.removeChild(document.documentElement);

jsFiddle.

js小提琴

Note that the browser will leave the doctype intact.

请注意,浏览器将保持 doctype 不变。

回答by user123444555621

Setting document's innerHTMLis officially supported in HTML5, but not in HTML4.

设置documentinnerHTML在HTML5正式支持,但不是在HTML4。

This should work in HTML4:

这应该适用于 HTML4:

var html = document.documentElement;
while(html.firstChild){
    html.removeChild(html.firstChild);
}

回答by XP1

Although not cross browser, Opera has a writable outerHTMLproperty.

虽然不是跨浏览器,但 Opera 具有可写outerHTML属性。

document.documentElement.outerHTML = "";

回答by sam sha

here is useful example, not perfect but can use

这是有用的例子,不完美但可以使用

/**
 * clear child nodes
 * @param {HTMLElement} node
 */
    clearChildren : function(node) {
        if (!node) {
            return;
        }
        if(node.innerHTML){
            node.innerHTML = '';
            return;
        }
        while (node.childElementCount > 0) {
        var child = node.childNodes.item(0);
        if(isIE){
            child.onmousedown = null;
            child.onmouseover = null;
            child.onmouseout = null;
            child.onclick = null;
            child.oncontextmenu = null;
        }
        node.removeChild(child);
    }
    }

回答by Maciej Krawczyk

It can be much simpler

它可以简单得多

document.write();