Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
How to remove HTML
<body>
element with all of its content?
var e = document.getElementsByTag('html');
e.removeChild('body');
Does not work.
–
–
–
–
–
–
var html = document.getElementsByTagName('html')[0];
var body = document.getElementsByTagName('body')[0];
html.removeChild(body);
–
–
while(document.body.childNodes.length != 0) {
document.body.removeChild(document.body.childNodes[0])
–
Try this code it will remove all the content of body tag on click on the button
And if you want to remove content onload then use this onload="document.body.innerHTML = '';"
This is example Text<br>
<button onclick="document.body.innerHTML = '';">Click me to remove body contents</button>
</body>
</html>
Several people on this page have asked why one might even wish to remove a <body>
element from an HTML Document
.
Admittedly, it's a seldom-seen approach, but it's almost always because one wishes to remove the current <body>
from a document (while keeping the <head>
) and then create a new <body>
element (to follow the same <head>
as before).
So why not, simply empty the existing <body>
element via:
document.body.innerHTML = '';
while (HTMLSourceTab.document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
The answer might be:
If the HTML Document
in question is being opened in a new browser tab, these processes (above) can only execute after the DOMContentLoaded
event fires.
And they may not execute quickly enough to prevent a brief Flash Of Legacy Body.
Whereas:
document.body.remove();
will normally execute quickly enough after DOMContentLoaded
to prevent that flash.
Once the legacy <body>
has been removed, a new <body>
can be created and added via:
let newBody = document.createElement('body');
document.documentElement.appendChild(newBody);
or (if adding an empty <body>
) simply:
document.body = document.createElement('body');
Full code for opening an existing document in a new tab, removing the existing <body>
and adding a new <body>
:
myNewTab = window.open(myNewTabURL, '_blank');
myNewTab.addEventListener('DOMContentLoaded', () => {
myNewTab.document.body.remove();
setTimeout(() => myNewTab.document.body = myNewTab.document.createElement('body'), 800);
myNewTab.focus();
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.