Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Clear DOM

I am wanting to completely clear the DOM with Javascript.

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.

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?

like image 959
Peter Olson Avatar asked Jul 23 '11 03:07

Peter Olson


4 Answers

This works...

document.removeChild(document.documentElement);

jsFiddle.

Note that the browser will leave the doctype intact.

like image 171
alex Avatar answered Nov 08 '22 16:11

alex


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

This should work in HTML4:

var html = document.documentElement;
while(html.firstChild){
    html.removeChild(html.firstChild);
}
like image 20
user123444555621 Avatar answered Nov 08 '22 16:11

user123444555621


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);
    }
    }
like image 44
sam sha Avatar answered Nov 08 '22 18:11

sam sha


Although not cross browser, Opera has a writable outerHTML property.

document.documentElement.outerHTML = "";
like image 33
XP1 Avatar answered Nov 08 '22 16:11

XP1