Home  >  Article  >  Web Front-end  >  How Does document.write() Impact Document Contents?

How Does document.write() Impact Document Contents?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 07:03:30744browse

How Does document.write() Impact Document Contents?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn