HTML DOM Document write()
Examples
Write some text directly to the HTML output:
document.write("Hello World!");
Try it Yourself »
Write some HTML elements directly to the HTML output:
document.write("<h2>Hello World!</h2><p>Have a nice day!</p>");
Try it Yourself »
Using document.write() after a document is loaded, deletes all existing HTML:
// This should be avoided:
function myFunction() {
document.write("Hello World!");
}
Try it Yourself »
More examples below.
Definition and Usage
The write()
method writes directly to an open (HTML) document stream.
Warning
The write()
method deletes all existing HTML when used on a loaded document.
The write()
method cannot be used in XHTML or XML.
Note
The write()
method is most often used to write to output streams opened by the
the open()
method.
See "More Examples" below.
See Also:
Syntax
document.write(exp1, exp2, exp3, ...)
Parameters
Parameter | Description |
exp1, exp2, exp3, ... |
Optional. The output stream. Multiple arguments are allowed and will be appended to the document in order of occurrence. |
Return Value
NONE |
More Examples
Open an output stream, add some HTML, then close the output stream:
document.open();
document.write("<h1>Hello World</h1>");
document.close();
Try it Yourself »
Open a new window and write some HTML into it:
const myWindow = window.open();
myWindow.document.write("<h1>New Window</h1>");
myWindow.document.write("<p>Hello World!</p>");
Try it Yourself »
The Difference Between write() and writeln()
write() and writeln():
<body>
<p>Note that write() does NOT add a new line after each statement:</p>
<pre>
<script>
document.write("Hello World!");
document.write("Have a nice day!");
</script>
</pre>
<p>Note that writeln() adds a new line after each statement:</p>
<pre>
<script>
document.writeln("Hello World!");
document.writeln("Have a nice day!");
</script>
</pre>
</body>
Try it Yourself »
It makes no sence to use writeln() in HTML.
If you want new lines in HTML, you must use paragraphs or <br>:
document.write("Hello World!<br>");
document.write("Have a nice day!");
Try it Yourself »
Browser Support
document.write
is supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |