Why does document.write () empty the page?

document.write("");
document.write("");
document.write("");
document.write("");
document.write("");

Why does this code, the latter one, output the complete sentence "I am a flower" instead of emptying the content shown in the previous sentence?

Nov.24,2021

because calling document.write in the method will first implicitly call document.open , and open will reopen the document object stream and start (overwrite) writing . So calling write within a method causes the contents of document to be overwritten.

if your code looks like this, H1 and the button will exist at the same time, because the write method is executed at render time, and because the document stream is open at this time, the new content is appended to the stream. But everything disappears when you click the button.


<script>
  document.write("<h1>Hello</h1>");
    function sayHello(){
      document.open();
      document.close();
    }
</script>
Menu