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

Why Does document.write() Clear the Page?

Susan Sarandon
Release: 2024-10-24 06:59:30
Original
751 people have browsed it

Why Does document.write() Clear the Page?

Why Does Document.write Clear the Page?

When using the document.write() method in JavaScript, programmers often encounter a peculiar behavior: invoking document.write() within an event handler, such as onClick, may result in the document being cleared.

To understand this unexpected outcome, it's essential to grasp the nature of document.write(). This function writes to the document stream, which is the continuous flow of data representing the document being displayed in the browser.

In the provided code example:

<code class="html"><form name="myForm">
    <input type="checkbox" name="thebox" />
    <input type="button" onClick="validator()" name="validation" value="Press me for validation" />
</form>

<script type="text/javascript">
    function validator() {
        if (document.myForm.thebox.checked) {
            document.write("checkBox is checked");
        } else {
            document.write("checkBox is NOT checked");
        }
    }
</script></code>
Copy after login

The validator() function is triggered when the "validation" button is clicked. Here's what happens:

  1. At this point, the document has likely finished loading, which means the document stream is closed.
  2. Invoking document.write() automatically triggers document.open(), which clears the current document, removing all existing elements.
  3. Subsequently, the text specified in document.write() is rendered in the now-empty document.

Consequently, the form elements (checkbox and button) are removed from the page because the entire document is refreshed, replacing the previous contents with the output of document.write().

Therefore, when working with document.write(), it's crucial to ensure that the document stream remains open by using document.open() explicitly before writing to it. Otherwise, the unpredictable behavior of clearing the document can disrupt intended functionality.

The above is the detailed content of Why Does document.write() Clear the Page?. 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!