JavaScript Document writeln() Method

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

What You’ll Learn

document.writeln() is a Deprecated instance method that writes one or more HTML strings (or TrustedHTML values) into a document stream opened by document.open(), then appends a newline (see MDN Document: writeln()). Learn how that newline only shows in whitespace-preserving elements, how it compares to write(), 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

Extra

+ newline

05

Risk

XSS sink

06

Status

Deprecated

Introduction

writeln() belongs to the same legacy document stream family as write():

  1. document.open() — start (and often clear) the stream.
  2. document.writeln(...) — push markup, then a newline character.
  3. document.close() — finish writing so parsing can complete.

MDN: the method is essentially the same as document.write() but adds a newline. That newline is only visible if it lands inside an element where newlines are displayed (MDN highlights <pre>).

⚠️
Never practice on the live tutorial page

Like write(), a late writeln() can auto-open() and wipe the current page. Labs use an iframe’s contentDocument so only the preview is replaced.

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

Understanding document.writeln()

An instance method on Document (dynamic markup insertion with a trailing newline).

  • Parameters — one or more markup strings or TrustedHTML values (MDN).
  • Return valueundefined (MDN).
  • vs write() — same stream behavior, plus a newline after the written text (MDN).
  • Newline visibility — only noticeable in elements that preserve whitespace (for example <pre>) (MDN).
  • After load — same wipe risk as write() via auto-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 (MDN).

📝 Syntax

General forms of Document.writeln (MDN):

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

Parameters

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

Return value

None (undefined) (MDN).

Exceptions

  • InvalidStateError-style cases on MDN include calling on an XML document, or while a custom element constructor is running (see MDN).
  • 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.writeln("<pre>Line A");
doc.writeln("Line B</pre>");
doc.close();

⚡ Quick Reference

GoalCode / note
Safe practice targetiframe.contentDocument (not the live page)
Full streamdoc.open(); doc.writeln(...); doc.close();
See the newlineWrite into a <pre> (MDN)
Multiple chunksdoc.writeln(a, b)
Modern replace childrenel.replaceChildren(...) / createElement
Trusted Typesdoc.writeln(policy.createHTML(html)) (MDN)
MDN statusDeprecated

🔍 At a Glance

Four facts about document.writeln().

Returns
undefined

MDN

Extra
\\n

newline

Pairs
open/close

stream

Status
Deprecated

MDN

📋 When the extra newline matters

Where you injectwriteln() newlineBeginner tip
Inside <pre>Usually visible as a line breakBest place to demo the difference from write()
Inside normal <p> / flow layoutOften collapsed like HTML whitespaceLooks almost identical to write()
After the document has loadedStill can wipe via auto-openPractice only on an iframe
With untrusted stringsXSS risk (MDN)Never do this

Examples Gallery

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

📚 Getting Started

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

Example 1 — open → writeln → close

Build a small preview document with writeln into a <pre>.

JavaScript
const doc = document.getElementById("preview").contentDocument;
doc.open();
doc.writeln("<pre>Hello world!");
doc.writeln("I am a fish");
doc.writeln("The number is 42</pre>");
doc.close();
console.log("pre text:", doc.querySelector("pre").textContent);
Try It Yourself

How It Works

Each writeln() adds markup plus a newline. Inside <pre>, those newlines become visible line breaks (MDN).

Example 2 — writeln() vs write() in a pre

Side-by-side comparison so the trailing newline is obvious.

JavaScript
const doc = document.getElementById("preview").contentDocument;
doc.open();
doc.write("<pre id='a'>");
doc.write("write:");
doc.write("same-line");
doc.write("</pre><pre id='b'>");
doc.writeln("writeln:");
doc.writeln("next-line");
doc.write("</pre>");
doc.close();
Try It Yourself

How It Works

MDN’s key teaching point: writeln() equals write() plus a newline. Comparing both inside <pre> makes that difference concrete.

📈 Practical Patterns

MDN-style multi-call pre content, the after-load wipe trap, and a modern replacement.

Example 3 — Split strings across writeln calls (MDN style)

MDN writes heading and pre content across several writeln calls.

JavaScript
const doc = document.getElementById("preview").contentDocument;
const one = "<h1>Out with";
const two = "the old</h1>";
const three = "<pre>in with";
const four = "the new!</pre>";

doc.open();
doc.writeln(one);
doc.writeln(two, three);
doc.writeln(four);
doc.close();
Try It Yourself

How It Works

Arguments concatenate in order. MDN’s Trusted Types demo wraps each string with policy.createHTML(...) when enforcement is on.

Example 4 — After-load writeln can wipe a document

Demonstrate auto-open behavior on an iframe document only.

JavaScript
const doc = document.getElementById("preview").contentDocument;
doc.open();
doc.writeln("<p id='keep'>Original iframe content</p>");
doc.close();

document.getElementById("wipe").addEventListener("click", () => {
  // Late writeln on a loaded document can open() and replace it.
  doc.writeln("<p>Replaced via late writeln()</p>");
  doc.close();
});
Try It Yourself

How It Works

Same trap as write(): after load, stream methods can clear the document. Keep experiments inside an iframe.

Example 5 — Prefer createElement + textContent

Multi-line text without a deprecated stream API.

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

const pre = document.createElement("pre");
pre.textContent = "Out with the old\nin with the new!";
host.append(pre);
Try It Yourself

How It Works

Put real \n characters in textContent. You get visible newlines in a <pre> without parsing HTML strings.

🚀 Common Use Cases

  • Legacy literacy — recognize Deprecated writeln() next to write() (MDN).
  • Teaching newlines — show why a trailing \n only matters in whitespace-preserving elements.
  • Iframe previews — rebuild a sandbox document with open/writeln/close for demos.
  • Explaining auto-open — teach why late stream writes wipe pages.
  • Trusted Types training — show writeln as an HTML injection sink (MDN).
  • Not for production UI — migrate to modern DOM APIs.

🧠 How writeln() Works

1

A document stream is open

Via document.open(), or implicitly after load (same family as write).

Open
2

writeln() parses markup

Strings / TrustedHTML become DOM nodes, then a newline is added (MDN).

Write + \\n
3

close() finishes the stream

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

Close
4

Prefer modern DOM for real apps

Keep writeln() as literacy — ship createElement / textContent instead.

📝 Notes

  • MDN: marked Deprecated.
  • Not marked Experimental or Non-standard on MDN, but still unsuitable for new products.
  • Essentially write() + newline; newline visibility depends on the target element (MDN).
  • Late writeln() 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: write(), open(), close(), createElement().

Deprecated Browser Support

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

Deprecated · Legacy

Document.writeln()

Write markup into a document stream, then a newline. 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*
writeln() Avoid in new apps

Bottom line: Learn open/writeln/close for literacy. Demo newlines inside pre. Never inject untrusted HTML. Rebuild UI with createElement, textContent, and append instead.

Conclusion

document.writeln() is a Deprecated stream writer that behaves like write() with an extra newline. Learn it for legacy literacy, demo the newline inside a <pre>, respect wipe and XSS risks, then build with modern DOM APIs.

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

💡 Best Practices

✅ Do

  • Treat this as legacy literacy (MDN)
  • Experiment only on iframe documents
  • Demo newlines inside <pre> when comparing to write()
  • Call open()writeln()close() as one unit
  • Migrate to createElement / textContent / append

❌ Don’t

  • Use writeln() in new products (MDN)
  • Call it on the live page after load
  • Pass untrusted user HTML strings
  • Expect newlines to show in normal paragraphs
  • Confuse document.writeln with console logging

Key Takeaways

Knowledge Unlocked

Five things to remember about writeln()

Deprecated write-plus-newline stream API.

5
Core concepts
📄02

vs write

+ newline

MDN
🗎03

Visible in

<pre>

whitespace
🛡04

Security

XSS sink

MDN
⚠️05

Status

Deprecated

MDN

❓ Frequently Asked Questions

MDN: Document.writeln() writes text in one or more TrustedHTML or string parameters to a document stream opened by document.open(), followed by a newline character.
MDN: writeln() is essentially the same as document.write() but adds a newline after the written text. That newline is only visible when injected inside an element that displays newlines (for example a pre).
Yes. MDN marks Document.writeln() as Deprecated. Prefer modern DOM APIs such as createElement, textContent, append, or carefully sanitized HTML insertion.
None (undefined) (MDN).
Yes. MDN: writeln() 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.writeln() on the live tutorial page. Use an iframe’s contentDocument with open(), writeln(), and close(), as in the try-it labs.
Did you know?

MDN notes that the newline from document.writeln() is only visible when it is injected inside an element where newlines are displayed. That is why demos usually write into a <pre> — in a normal paragraph the extra newline often collapses like ordinary HTML whitespace.

Next: exitFullscreen()

Learn how to leave fullscreen mode with document.exitFullscreen() and its Promise.

exitFullscreen() →

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