JavaScript document.write() and Why It Can Clear a Page

document.write() writes a string to the HTML document’s input stream. During parsing it can insert content at the current position. After the page loads, it can reopen the document and clear existing content. To update one part of the page, target that element with DOM methods.

What document.write() does during parsing

Save the code as document-write-legacy.html in UTF-8 and open it in a browser. The inline script runs while the HTML is being parsed. Its two arguments are concatenated and parsed as one paragraph, so Hello World appears between the surrounding paragraphs. For the newline variant, see how document.writeln() adds a newline.

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Try document.write</title></head>
<body>
  <p>Paragraph before the script</p>
  <script>
    document.write('<p id="written">Hello ', 'World</p>');
  </script>
  <p>Paragraph after the script</p>
</body>
</html>

Why existing content can disappear after load

If there is no parser insertion point, document.write() can implicitly open the document as if document.open() had been called. This can clear the existing page. Some asynchronous script calls are ignored, so the same call in an event handler does not always have the same outcome. HTML Standard · document.write()

The method interprets strings as HTML and does not sanitize them. To display user input as plain text, assign it to textContent. Characters that resemble markup remain visible as text.

Update only the output area with DOM methods

Save dom-output.html in UTF-8 and open it in a browser. The show button makes a paragraph with createElement('p') and assigns the input to textContent. replaceChildren(paragraph) replaces just the output area’s existing children. DOM Standard · replaceChildren()

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Display text in part of a document</title>
</head>
<body>
<label for="message">Text to display</label>
<input id="message" value="Hello World">
<button id="show" type="button">Show</button>
<button id="clear" type="button">Clear</button>
<div id="output" aria-live="polite"></div>
<script>
const input = document.querySelector('#message');
const output = document.querySelector('#output');

document.querySelector('#show').addEventListener('click', () => {
  const paragraph = document.createElement('p');
  paragraph.textContent = input.value;
  output.replaceChildren(paragraph);
});
document.querySelector('#clear').addEventListener('click', () => {
  output.replaceChildren();
});
</script>
</body>
</html>

The default input displays Hello World. Change it to 2 < 3 & 4 > 1 to see the symbols preserved. Repeated clicks still leave one output paragraph. Clear removes the output while leaving the input and buttons in place.