Skip to content

JavaScript document open | Method

  • by

JavaScript Document open() method is opens a document for writing. The difference between open() and write() is that open() clears the document so you can write to it. write() actually puts stuff in the document.

open()
document.open() 

Note: All existing document content will be cleared.

JavaScript document open

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    document.open();
    document.write("<h3>Hello World</h3>");
    document.close();
    document.write("Closed")
  </script>

</body>
</html>

Output:

JavaScript document open Method

If document.write() is used on a closed document, document.open() is automatically called. This will delete existing content.

document.write("<h1>Hello World!</h1>");

Are document.open and document.close necessary?

Answer: Explicitly calling document.open()/document.close() is not necessary as document.write() implicitly handles open() when the page has loaded and close() when finished.

Code…

var msg = "Hello, World!";
document.open();
document.write(msg);
document.close();

…has the same result as this one:

var msg = "Hello, World!";
document.write(msg);

Do comment if you have any doubts or suggestions on this Js document method tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *