JavaScript - open() method

revision:


Category : document

The Document.open() method opens a document for writing.

This does come with some side effects. For example: all event listeners currently registered on the document, nodes inside the document, or the document's window are removed; all existing nodes are removed from the document.

Syntax :

       open(())
    

Parameters: none

Examples:

            document.open();
            document.write("<p>Hello world!</p>");
            document.write("<p>I am a fish</p>");
            document.write("<p>The number is 42</p>");
            document.close();
        

Practical examples

example: open this document, write some text, and close.

Open a document deletes existing content.

Open this document and write some text to it:

code:
                    <div>
                        <p>Open a document deletes existing content.</p>
                        <p>Open this document and write some text to it:</p>
                        <button onclick="openFunction()">Try it</button>
            
                    </div>
                    <script>
                        function openFunction() {
                            document.open();
                            document.write("<h1>Hello World</h1>");
                            document.close();
                        }   
                    </script>
                

example: using document.open() in a new window.

Click "Open" to open a document in a new window, write some text to it and close it:

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