Home > Web Front-end > JS Tutorial > body text

How Does document.write() Impact Document Contents?

Mary-Kate Olsen
Release: 2024-10-24 07:03:30
Original
743 people have browsed it

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!