Document.write() Effects on Document Content
The document.write() method alters the contents of an HTML document by directly writing to the document stream. In certain scenarios, this action can lead to the removal of previously displayed elements.
For instance, consider the following code:
<code class="html"><!DOCTYPE html> <html> <head> <script type="text/javascript"> function validator() { if (document.myForm.thebox.checked) document.write("checkBox is checked"); else document.write("checkBox is NOT checked"); } </script> </head> <body> <form name="myForm"> <input type="checkbox" name ="thebox"/> <input type="button" onClick="validator()" name="validation" value="Press me for validation"/> </form> </body> </html></code>
When the validator() function is called, the document.write() method is used to output a message to the document. However, upon doing so, the form elements (the checkbox and button) disappear from the screen.
This behavior occurs because document.write() operates on the document stream. When called after the document has finished loading, it may cause the stream to be closed. Consequently, to write to the stream, document.write() automatically opens the document again, which resets the page content, removing all existing elements.
The above is the detailed content of How Does document.write() Impact Document Contents?. For more information, please follow other related articles on the PHP Chinese website!