2

I'm searching a js one-liner to delete everything inside the <html> Tag.

I want to remove the <head>, the <body> and everything else declared outside those.

John
  • 75
  • 2
  • 8

5 Answers5

5

document.write() will create empty page, or actually the following code:

<html>
  <head></head>
  <body></body>
</html>

But I am not sure if this won't clash if the code will be in external file

Zefiryn
  • 2,240
  • 2
  • 20
  • 30
3

It's not an oneliner, but it does the job you're asking for.

document.open();
document.write("");
document.close();
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • No need to open and close the document. Simply calling document.write(), as @Zefiryn mentioned, does the trick. Thanks for your answer – John Oct 02 '12 at 20:23
  • @John It may appear to work, but I've had problems without using `open` and `close`...which is possible that you may not encounter. – Ian Oct 02 '12 at 20:30
  • It'll maybe work "perfectly fine" in context of a Chrome Extension script (I can't tell about that from experience; for instance, perhaps Chrome has already implicitly done `document.open()` for you), but it'll not reliably work in context of a normal JS function/script, at least not if you want to keep it cross browser compatible. – BalusC Oct 02 '12 at 20:30
  • Ah, many thanks for pointing this out @BalusC ! I'm only using this in context of a Chrome Extension. – John Oct 02 '12 at 20:44
2

1 liner :)

window.onload = function(){ document.getElementsByTagName("html")[0].innerHTML = "";};
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

Once your HTML page is loaded, the javascript is loaded into the browser memory. So if you are to load jQuery for instance, you can simply call;

$('html').empty();

Give it a try using Google Chrome's Javascript Console. Type the above code, then you can still access jQuery and manipulate the DOM.

Edit

To answer your comment John. You have not stated in your question that jQuery cannot be used.

Tim B James
  • 20,084
  • 4
  • 73
  • 103
  • 1
    +1 Also, @John, almost *everywhere* on SO, where a library is disallowed, it's explicitly stated in the question. Simply saying "js" doesn't presume "vanilla EMCAScript". – msanford Oct 03 '12 at 03:25
  • @msanford unfortunately some people do not know how to construct a good question and others Down vote without thinking. Thanks for +1! – Tim B James Oct 03 '12 at 07:40
0

Not really a good idea, but this worked for me.

First, wrap all the elements in a div element with a id.

I made a div with the id wrapper.

Then:

let doc = document.getElementById("wrapper");
doc.innerHTML = "";
fg_
  • 59
  • 1
  • 8