A point in the use of document.write in js

  • 2020-03-30 02:25:00
  • OfStack

I was a novice, so I wrote it down. This answer is seen in baidu, so it is reproduced.

The following explains why if you call document.write after the page has loaded it will overwrite the entire document.

The "in the HTML output" in the prompt refers to when the page loads.
 
<html> 
<head></head> 
<body> 
<script type="text/javascript">document.write("<p>Hello</p>");</script> 
</body> 
</html> 

When the page loads, you will see Hello on the page. Viewing the source file is the code above.

-------------------------

But if the page is loaded and document.write is used, it overwrites the entire document.
 
<html> 
<head></head> 
<body> 
<script type="text/javascript"> 
//Document.write is called when the mouse is clicked
document.onclick = function() { 
document.write("<span>Javascript</span>"); 
}; 
</script> 
</body> 
</html> 

Because the mouse action is performed after the page has been loaded, the entire page is Span> Javascript< / span> Covered. Now if you look at the source file you will see only Span> Javascript< / span> .

Related articles: