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.


Description

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 Also:

The Document open() Method

The Document close() Method

The Document writeln() Method


Syntax

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

Parameters

Parameter Description
exp1,... Optional.
The output stream.
Multiple arguments are appended to the document in order of occurrence.

Return Value

NONE

More Examples

Write a date object directly to the HTML ouput:

document.write(Date());
Try it Yourself »

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()

The writeln( ) method is only useful when writing to text documents (type=".txt").

Example

document.write("Hello World!");
document.write("Have a nice day!");
document.write("<br>");
document.writeln("Hello World!");
document.writeln("Have a nice day!");
Try it Yourself »

Note

It makes no sense to use writeln() in HTML.

It is only useful when writing to text documents (type=".txt").

Newline characters are ignored in HTML.

If you want new lines in HTML, you must use paragraphs or <br>:

Examples

document.write("Hello World!");
document.write("<br>");
document.write("Have a nice day!");
Try it Yourself »
document.write("<p>Hello World!</p>");
document.write("<p>Have a nice day!</p>");
Try it Yourself »

Browser Support

document.write is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.