MyInternships.in

HTML DOM

HTML DOM close() Method

The close() method closes an output stream that was previously opened with document.open() and forces any buffered content to be displayed. It is used together with document.open() and document.write().


Definition and Usage

document.close() closes the document stream that document.open() started. After you write content to a document with document.write(), calling close() tells the browser you are finished so it can finish rendering the page and stop showing a loading indicator.

If you write to a document that has already finished loading, the browser implicitly calls document.open() first, which erases the existing page. close() then finalises that new content.

Syntax

document.close()

Example

This example opens a new document stream, writes some HTML into it, and then closes the stream. Click the button and the whole page is replaced by the written content.

open, write, then close a document
Example
<!DOCTYPE html>
<html>
<body>
  <button onclick="rewrite()">Rewrite this page</button>

  <script>
    function rewrite() {
      document.open();
      document.write("<h1>Fresh content</h1>");
      document.write("<p>The old page is gone.</p>");
      document.close();
    }
  </script>
</body>
</html>

More Examples

close() is commonly used when writing into another window or iframe document. Here we build a small popup document and close its stream so it renders.

Write into a new window and close it
Example
<!DOCTYPE html>
<html>
<body>
  <button onclick="openWin()">Open popup</button>

  <script>
    function openWin() {
      const w = window.open("", "", "width=300,height=200");
      w.document.open();
      w.document.write("<h2>Hello from a new window</h2>");
      w.document.close();
    }
  </script>
</body>
</html>
⚠️

document.write() and document.close() replace the entire page if called after loading. They are legacy tools - modern code should build DOM nodes with createElement and appendChild instead.

Key Takeaways

  • close() finalises a stream opened with document.open().
  • It forces buffered content written with document.write() to display.
  • Writing to a loaded page implicitly reopens and clears it.
  • It is legacy API - prefer DOM creation methods in new code.

Related HTML Topics

Keep learning with these closely related tutorials.

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships