JavaScript Document write() Method

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Deprecated
Instance method

What You’ll Learn

document.write() is a Deprecated instance method that writes one or more HTML strings (or TrustedHTML values) into a document stream opened by document.open() (see MDN Document: write()). Learn the classic open()write()close() pattern, post-load wipe risks, XSS / Trusted Types notes, safer alternatives, and five iframe-based try-it labs.

01

Kind

Instance method

02

Args

1+ markup strings

03

Returns

undefined

04

Pairs with

open / close

05

Risk

XSS sink

06

Status

Deprecated

Introduction

Early web scripts often built pages by writing HTML into a document stream:

  1. document.open() — start (and often clear) the stream.
  2. document.write(...) — push markup strings into that stream.
  3. document.close() — finish writing so parsing can complete.

MDN: write() writes text in one or more TrustedHTML or string parameters to a document stream opened by document.open().

⚠️
Never practice on the live tutorial page

Calling document.write() after load can auto-open() and wipe the current page. Labs use an iframe’s contentDocument so only the preview is replaced.

Related tutorials: open(), close(), createElement(), clear().

Understanding document.write()

An instance method on Document (dynamic markup insertion).

  • Parameters — one or more markup strings or TrustedHTML values (MDN).
  • Return valueundefined (MDN).
  • Stream — writes into a stream opened by document.open() (MDN).
  • After load — a lone write() may call open() automatically and clear the document (MDN Notes on open()).
  • Injection sink — parses HTML; XSS risk if input is untrusted (MDN).
  • Trusted Types — when enforced, strings can throw TypeError unless a policy creates TrustedHTML (MDN).
  • Status — Deprecated; strongly discouraged (MDN).

📝 Syntax

General forms of Document.write (MDN):

JavaScript
write(markup)
write(markup, markup2)
write(markup, markup2, /* …, */ markupN)

Parameters

  • markup, …, markupNTrustedHTML or string objects containing the text to write to the document (MDN).

Return value

None (undefined) (MDN).

Exceptions

  • TypeError — a string is passed when Trusted Types are enforced and no default policy exists for creating TrustedHTML (MDN).

Classic stream pattern

JavaScript
const doc = iframe.contentDocument;
doc.open();
doc.write("

Hello world!

"); doc.write("

I am a fish

"); doc.close();

⚡ Quick Reference

GoalCode / note
Safe practice targetiframe.contentDocument (not the live page)
Full streamdoc.open(); doc.write(...); doc.close();
Multiple chunksdoc.write(a, b, c)
Modern replace childrenel.replaceChildren(...) / createElement
Trusted Typesdoc.write(policy.createHTML(html)) (MDN)
MDN statusDeprecated — strongly discouraged

🔍 At a Glance

Four facts about document.write().

Returns
undefined

MDN

Args
markup+

strings

Pairs
open/close

stream

Status
Deprecated

MDN

📋 During parse vs after load

When you call write()Typical effectBeginner tip
Inline while the parser is runningInjects into the parsing stream (legacy pattern)Still discouraged; blocks / quirks possible
After the document has loadedMay auto-open() and clear everythingLooks like the page “vanished”
On an iframe document you openedRebuilds only that iframeBest way to experiment safely
With untrusted stringsXSS / script injection risk (MDN)Never do this

Examples Gallery

Examples follow MDN Document: write() and the related open/close stream. Prefer iframe demos.

📚 Getting Started

Write into an iframe document stream without touching the host page.

Example 1 — open → write → close

MDN-style stream into a preview iframe.

JavaScript
const doc = document.getElementById("preview").contentDocument;
doc.open();
doc.write("

Hello world!

"); doc.write("

I am a fish

"); doc.write("

The number is 42

"); doc.close(); console.log("paragraphs:", doc.querySelectorAll("p").length);
Try It Yourself

How It Works

open() starts a fresh stream; write() adds markup; close() finishes it.

Example 2 — Multiple markup arguments

MDN allows several strings in one call.

JavaScript
const doc = document.getElementById("preview").contentDocument;
const one = "

Out with the old

"; const two = "

in with the new!

"; doc.open(); doc.write(one, two); doc.close();
Try It Yourself

How It Works

Arguments are written in order. MDN examples also show wrapping strings with a Trusted Types policy when enforcement is on.

📈 Practical Patterns

Inline legacy usage, the after-load wipe trap, and a modern replacement.

Example 3 — Inline write while parsing (legacy)

MDN shows a script that writes a heading during parse.

JavaScript
<script>
  document.write("<h1>Main title</h1>");
</script>
Try It Yourself

How It Works

This is the historic “write into the parser” style. MDN still discourages it for new projects.

Example 4 — After-load write can wipe a document

Demonstrate auto-open behavior on an iframe document only.

JavaScript
const doc = document.getElementById("preview").contentDocument;
doc.open();
doc.write("

Original iframe content

"); doc.close(); // Later, after that document is loaded: document.getElementById("wipe").addEventListener("click", () => { // Calling write on a loaded document can open() and replace it (MDN). doc.write("

Replaced via late write()

"); doc.close(); });
Try It Yourself

How It Works

This is the classic beginner bug when someone calls document.write() from a button on the main page.

Example 5 — Prefer createElement + append

Same visual result without a deprecated stream API.

JavaScript
const host = document.getElementById("host");
host.replaceChildren();

const h1 = document.createElement("h1");
h1.textContent = "Out with the old";
const p = document.createElement("p");
p.textContent = "in with the new!";
host.append(h1, p);
Try It Yourself

How It Works

Text goes through textContent, so you avoid accidental script injection from string HTML.

🚀 Common Use Cases

  • Legacy literacy — recognize Deprecated stream APIs in old scripts (MDN).
  • Iframe previews — rebuild a sandbox document with open/write/close for demos.
  • Explaining auto-open — teach why late write() wipes pages.
  • Trusted Types training — show write as an HTML injection sink (MDN).
  • Not for production UI — MDN strongly discourages new use.
  • Migration target — replace with createElement / append / frameworks.

🧠 How write() Works

1

A document stream is open

Via document.open(), or implicitly after load (MDN).

Open
2

write() parses markup

Strings / TrustedHTML become DOM nodes in the stream (MDN).

Write
3

close() finishes the stream

Best practice: always close after writing (see close()).

Close
4

Prefer modern DOM for real apps

Keep write() as literacy — ship createElement / append instead.

📝 Notes

  • MDN: marked Deprecated; use is strongly discouraged.
  • Not marked Experimental or Non-standard on MDN, but still unsuitable for new products.
  • Late write() can auto-open() and clear the document.
  • HTML injection sink — XSS risk; prefer TrustedHTML when Trusted Types are enforced (MDN).
  • Practice on iframe.contentDocument, never on the live tutorial page.
  • Related: open(), close(), createElement(), replaceChildren().

Deprecated Browser Support

Document.write() is Deprecated on MDN and strongly discouraged, but remains widely implemented for legacy compatibility. Logos use the shared browser-image-sprite.png sprite from this project.

Deprecated · Legacy

Document.write()

Write markup into a document stream opened by document.open(). Prefer modern DOM APIs for new code.

Legacy Deprecated
Google Chrome Supported (legacy)
Yes*
Mozilla Firefox Supported (legacy)
Yes*
Apple Safari Supported (legacy)
Yes*
Microsoft Edge Supported (legacy)
Yes*
Opera Supported (legacy)
Yes*
Internet Explorer Supported (legacy)
Yes*
write() Avoid in new apps

Bottom line: Learn open/write/close for literacy. Never inject untrusted HTML. Rebuild UI with createElement, append, and replaceChildren instead.

Conclusion

document.write() is a Deprecated stream writer that pairs with open() and close(). Learn it so legacy code makes sense, respect the after-load wipe and XSS risks, then build with modern DOM APIs.

Continue with open(), close(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Treat this as legacy literacy (MDN)
  • Experiment only on iframe documents
  • Call open()write()close() as one unit
  • Migrate to createElement / append / replaceChildren
  • Use Trusted Types if you must write HTML under enforcement (MDN)

❌ Don’t

  • Use write() in new products (MDN)
  • Call it on the live page after load
  • Pass untrusted user HTML strings
  • Assume parser quirks will match your source
  • Confuse document.write with console.log debugging

Key Takeaways

Knowledge Unlocked

Five things to remember about write()

Deprecated document-stream HTML writing.

5
Core concepts
📄02

Stream

open/write/close

pattern
🗑03

After load

can wipe

danger
🛡04

Security

XSS sink

MDN
⚠️05

Status

Deprecated

MDN

❓ Frequently Asked Questions

MDN: Document.write() writes text in one or more TrustedHTML or string parameters to a document stream opened by document.open().
Yes. MDN marks Document.write() as Deprecated and strongly discourages using it. Prefer modern DOM APIs such as createElement, textContent, append, or carefully sanitized HTML insertion.
None (undefined) (MDN).
MDN Notes (via Document.open): an automatic document.open() call can happen, which clears the existing document. That is why a late write() can wipe the whole page.
Yes. MDN: write() parses input as HTML and is an injection sink. Never pass untrusted user content. Prefer TrustedHTML when Trusted Types are enforced.
Do not call document.write() on the live tutorial page. Use an iframe’s contentDocument with open(), write(), and close(), as in the try-it labs.
Did you know?

MDN notes that a late document.write() after the page has loaded can trigger an automatic document.open(). That is why a single debugging write() can erase an entire page and look like a mysterious bug.

Next: writeln()

Learn document.writeln() — write() plus a newline, and when that newline is visible.

writeln() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful