Javascript Clear DOM

I want to completely clear the DOM with Javascript.

I tried several things, for example:

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

Interestingly, clearing the head like this will result in an error ("invalid target element for this operation") in IE, but will successfully clear the head in Chrome. However, body scrubbing like this works in IE but doesn't work in Chrome.

I 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?

+7
source share
5 answers

It works...

 document.removeChild(document.documentElement); 

jsFiddle .

Please note that the browser will not go without doctrine.

+11
source

here is a useful example, not perfect, but it 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); } } 
+2
source

document innerHTML customization 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); } 
+2
source

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

 document.documentElement.outerHTML = ""; 
+2
source

It could be a lot easier.

 document.write(); 
0
source

All Articles