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?
This works...
document.removeChild(document.documentElement);
jsFiddle.
Note that the browser will leave the doctype intact.
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);
}
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);
}
}
Although not cross browser, Opera has a writable outerHTML
property.
document.documentElement.outerHTML = "";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With