Home > Web Front-end > JS Tutorial > What are the Consequences of Using document.write() in JavaScript Functions?

What are the Consequences of Using document.write() in JavaScript Functions?

DDD
Release: 2024-10-24 07:38:02
Original
860 people have browsed it

What are the Consequences of Using document.write() in JavaScript Functions?

Document.write() Behavior in Function Calls

In an HTML document, calling document.write() within a function can have unexpected consequences, as seen in the following code:

<code class="html"><input type="checkbox" name="thebox" />
<input type="button" onClick="validator()" name="validation" value="Press me for validation" /></code>
Copy after login
<code class="javascript">function validator() {
    if (document.myForm.thebox.checked)
        document.write("checkBox is checked");
    else
        document.write("checkBox is NOT checked");
}</code>
Copy after login

Issue: After clicking the validation button, the form elements (checkbox and button) disappear from the page.

Explanation:

document.write() is a powerful function that writes directly to the HTML document's output stream. When called inside a function, document.write() has the following implications:

  • The document's output stream is likely already closed when the function is invoked because the document has finished loading.
  • Calling document.write() on a closed stream automatically opens the document, overwriting its existing content.

In this case, when validator() is called, document.write() automatically reopens the document, which clears the entire page, including the form elements.

Solution:

To avoid this behavior, one should use alternative methods to manipulate the document content, such as document.createElement() or the DOM manipulation APIs.

The above is the detailed content of What are the Consequences of Using document.write() in JavaScript Functions?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template