Skip to content

JavaScript document open | Method

  • by

JavaScript Document open() method 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading