JavaScript document.writeln() Newlines and the textContent Alternative

document.writeln() writes to the HTML document stream and appends a newline character, \n. An ordinary paragraph usually collapses that newline into whitespace. In new code, use textContent on a specific element and choose a display mode that preserves line breaks.

What write() and writeln() insert

document.write() adds no newline by itself. writeln() appends one after each call. In the example, A and B are adjacent, and a newline separates the following C.

document.write('A');
document.writeln('B');
document.write('C');

Both methods treat their input as HTML. Depending on the context, a call after the document loads can clear existing content. Use DOM methods for dynamic updates. HTML Standard · document.writeln()

When a legacy newline becomes visible

To inspect the old behavior, save the sample as writeln-legacy.html in UTF-8 and open it in a browser. With default styling, the newline between AB and C looks like a space in the paragraph and breaks the line inside <pre>. This example writes fixed strings during parsing.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Compare writeln line breaks</title>
</head>
<body>
  <p>Ordinary paragraph</p>
  <p id="normal"><script>document.write('A');
document.writeln('B');
document.write('C');</script></p>
  <pre id="preserved"><script>document.write('A');
document.writeln('B');
document.write('C');</script></pre>
</body>
</html>

On an ordinary element, CSS white-space: pre-wrap preserves line breaks while letting long lines wrap. Use <pre> for logs or code output where spacing matters. CSS Text · white-space

Update one element with textContent

Save the code below as text-content-lines.html in UTF-8 and open it. The show button joins the array with \n and replaces the text of <pre>. The clear button empties just the output area.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Display text on separate lines</title>
</head>
<body>
<button id="show" type="button">Show two lines</button>
<button id="clear" type="button">Clear</button>
<pre id="result" aria-live="polite"></pre>
<script>
const lines = ["First line", "<em>Second line</em>"];
const result = document.querySelector('#result');

document.querySelector('#show').addEventListener('click', () => {
  result.textContent = lines.join('\n');
});
document.querySelector('#clear').addEventListener('click', () => {
  result.textContent = '';
});
</script>
</body>
</html>

textContent inserts the string as text. The <em> notation in the sample appears literally. When you need an actual element, build it with createElement() and add it with append(). DOM Standard · Node.textContent