HTML DOM Document write() method
- Previous Page URL
- Next Page writeln()
- Go to the Previous Level HTML DOM Documents
Definition and usage
write()
This method directly writes to the opened (HTML) document stream.
Warning
write()
When used on a loaded document, this method will delete all existing HTML.
write()
This method cannot be used in XHTML or XML.
Tip:write()
This method is most commonly used to write to the output stream opened by the open() method. See the example below.
See also:
Example
Example 1
Directly write text to HTML output:
document.write("Hello World!");
Example 2
Directly write HTML elements to HTML output:
document.write("<h2>Hello World!</h2><p>Have a nice day!</p>");
Example 3
Use document.write() to delete all existing HTML after the document is loaded:
// Avoid this situation: function myFunction() { document.write("Hello World!"); }
Example 4
Write the date object directly to the HTML output:
document.write(Date());
Example 5
Open an output stream, add some HTML, and then close the output stream:
document.open(); document.write("<h1>Hello World</h1>"); document.close();
Example 6
Open a new window and write some HTML inside it:
const myWindow = window.open(); myWindow.document.write("<h1>New Window</h1>"); myWindow.document.write("<p>Hello World!</p>");
Syntax
document.write(exp1, exp2, exp3, ...)
Parameters
Parameters | Description |
---|---|
exp1, exp2, exp3, ... |
Optional. Output stream. Can accept multiple parameters and append them to the document in the order they appear. |
Return value
None.
Difference between write() and writeln()
writeln() adds a newline character at the end of each statement. write() does not.
Example
document.write("Hello World!"); document.write("Have a nice day!"); document.write("<br>"); document.writeln("Hello World!"); document.writeln("Have a nice day!");
Note
to use in HTML writeln() is meaningless. It is only useful when writing a plain text document (type=".txt"). Line breaks are ignored in HTML.
If you want to create a new line in HTML, you must useparagraphor <br>
:
Example 1
document.write("Hello World!"); document.write("<br>"); document.write("Have a nice day!");
Example 2
document.write("<p>Hello World!</p>"); document.write("<p>Have a nice day!</p>");
browser support
All browsers support document.write
:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support | Support |
- Previous Page URL
- Next Page writeln()
- Go to the Previous Level HTML DOM Documents