Does document.body.innerHTML = "" clear the web page?
Solution 1
document.body.innerHTML = '';
does clear the body
, yeah. But it clears the innerHTML
as it is at the moment the code is ran. As you run the code before the images and the script are actually in the body
, it tries to clear the body
, but there's nothing to clear.
If you want to clear the body
, you have to run the code after the body
has been filled with content. You can do this by either placing the <script>
block as the last child of body
, so everything is loaded before the code is ran, or you have to use some way to listen to the dom:loaded
event.
Solution 2
To expound on Douwem's answer, in your script tag, put your code in an onload:
<script type="text/javascript">
window.onload=function(){
document.body.innerHTML = "";
}
</script>
Solution 3
Whilst agreeing with Douwe Maan and Erik's answers, there are a couple of other things here that you may find useful.
Firstly, within your head tags, you can reference a separate JavaScript file, which is then reusable:
<script language="JavaScript" src="/common/common.js"></script>
where common.js is your reusable function file in a top-level directory called common.
Secondly, you can delay the operation of a script using setTimeout, e.g.:
setTimeout(someFunction, 5000);
The second argument is in milliseconds. I mention this, because you appear to be trying to delay something in your original code snippet.
Solution 4
As others were saying, an easy solution is to put your script at the bottom of the page, because all DOM elements are loaded synchronously from top to bottom. Otherwise, I think what you're looking for is document.onload(() => {callback_body})
or window.onload(() => {callback_body})
as Erik said. These allow you to execute you script when the dom:loaded
event is fired as Douwe Maan said. Not sure about the properties of window.onload
, but document.onload
is triggered only after all elements, css, and scripts are loaded. In your case:
<script type="text/javascript">
document.onload(() =>
document.body.innerHTML = "";
)
</script>
or, If you are using an old browser:
<script type="text/javascript">
document.onload(function() {
document.body.innerHTML = "";
})
</script>
Tony_Henrich
Updated on November 15, 2020Comments
-
Tony_Henrich over 3 years
When I refresh the page below in FF 3.0, I expected the web page to clear but it didn't.
Why doesn't
document.body.innerHTML = ""
clear the page?UPDATE: I am trying to clear the previous screen during a refresh while the new page is loading. I actually want to see the page clear, wait and then the next js running. I don't want to clear the screen after the page has loaded.
... <body> <script type="text/javascript"> document.body.innerHTML = ""; for (var i = 0; i < 1000000000; i++) { } </script> <img src="images/web.gif" /><br /> <script type="text/javascript"> document.write( "hello<br />"); </script> <img src="images/warning.png" /><br /> </body>