Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all content using pure JS

I'm looking for a way to remove the entire content of a web page using pure Javascript -- no libraries.

I tried:

document.documentElement.innerHTML = "whatever";

but that doesn't work: it replaces the inside of the <html/> element. I'm looking at replacing the entire document, including if possible the doctype and <?xml declaration.

like image 846
Félix Saparelli Avatar asked Nov 22 '10 00:11

Félix Saparelli


2 Answers

I think a browser rightfully assumes a page with content-type text/html will always be a web page - so whilst you may do something like...

document.body.innerHTML = '';

It will still have some HTML hanging around.

You could try...

document.documentElement.innerHTML = '';

...which left me with <html></html>.

Yi Jiang did suggest something clever.

window.location = 'about:blank';

This will take you to a blank page - an internal mechanism provided by most browsers I believe.

I think however the best solution is to use document.open() which will clear the screen.

like image 143
alex Avatar answered Sep 21 '22 02:09

alex


var i = document.childNodes.length - 1;

while (i >= 0) {
  console.log(document.childNodes[i]);
  document.removeChild(document.childNodes[i--]);
}

Removes everything (doctype also) on FF 3.6, Chrome 3.195, and Safari 4.0. IE8 breaks since the child wants to remove its parent.


Revisiting a while later, could also be done like this:

while (document.firstChild) {
  document.removeChild(document.firstChild);
}
like image 36
Ben Avatar answered Sep 21 '22 02:09

Ben