JavaScript - close() method

revision:


Category : document

The Document.close() method finishes writing to a document, opened with Document.open().

The close() method closes a window previously opened with the open() method.

Syntax :

       document.close()
    

Parameters: none

Examples:

            // Open a document to write to it
            document.open();
            // Write the content of the document
            document.write("<p>The one and only content.</p>");
            // Close the document
            document.close();

            <button onclick="myFunction()">Open</button>
            <script>
            function myFunction() {
                document.open();
                document.write("<h1>Hello World</h1>");
                document.write("<p>Open a document owerwrites the original content.</p>");
                document.close();
            }
            </script>
        

Practical examples

example: click "open" to open a document in a new window; write some text in it and close it
code:
                    <div>
                        <button onclick="writeFunction()">Try it</button>
                    </div>
                    <script>
                        function writeFunction() {
                            const myWindow = window.open();
                            myWindow.document.open();
                            myWindow.document.write("<h1>Hello World!</h1>");
                            myWindow.document.close();
                        }
                                    
                    </script>
                

example: click "open" to open a document in a new window; write some text in it and close it
code:
                    <div>
                        <button onclick="writeFunction2()">Try it</button>
                    </div>
                    <script>
                        function writeFunction2() {
                            document.open();
                            document.write("<h1>Hello World!</h1>");
                            document.write("<p>Open a document overwrites the original content.</p>");
                            document.close();
                        }
                                    
                    </script>