HTML DOM document.write()Method

Document 对象参考手册Document Object

Definition and Usage

document.write()The method can write text content to the document, which can be HTML code.

If it is executed after the document has finished loadingdocument.write(), the entire HTML page will be overwritten.

Syntax

document.write(exp1,exp2,exp3,...)

Parameters Description
exp1,exp2,exp3,... Optional. The output stream to write to. Multiple parameters can be listed; they will be appended to the document in the order they appear.

Note:document.write()The method writes a text string into andocument.open()opened document stream (document stream).

To a document that has already been loaded and has not calleddocument.open()when writing data to the document, it will automatically calldocument.open(). Once data writing is completed, it is recommended to call document.close() to tell the browser that the current page has finished loading. The written data will be parsed into the Document Object Model (DOM).

Ifdocument.write()the call occurs in a <script> tag in HTML, then it will not automatically calldocument.open(), as the following code:

<script>
document.write("<h1>Main title</h1>")
</script>


Browser Support

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

All major browsers support the write() method


Examples

Example 1

Write some text to the output stream:

document.write("Hello World!");

Try it Yourself »

Example 2

Write some HTML code text to the output stream:

document.write("<h1>Hello World!</h1><p>Have a nice day!</p>");

Try it Yourself »

Example 3

The difference between write() and writeln():

<p>Note that the write() method does not add a new line after each statement:</p> <script> document.write("Hello World!"); document.write("Have a nice day!"); </script> <p>Note that the writeln() method adds a new line after each statement:</p> <script> document.writeln("Hello World!"); document.writeln("Have a nice day!"); </script>

Try it Yourself »

Example 4

If the page has already loaded, it will overwrite the entire HTML document:

function myFunction() { document.write("Hello World"); }

Try it Yourself »

Example 4

Use open to open the document output stream, which will overwrite the entire HTML document:

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

Try it Yourself »

Example 5

You can open a new browser window and write content:

const myWindow = window.open(); myWindow.document.write("<h1>This is a new window</h1>"); myWindow.document.write("<p>Hello World!</p>");

Try it Yourself »


Document 对象参考手册Document Object Other Extensions