JavaScript の document.write() でページが消える理由と代替方法

document.write() は HTML 文書の入力ストリームに文字列を書き込みます。解析中は現在の位置に内容を挿入できます。読み込み後に呼び出すと文書を開き直し、既存の内容が消えることがあります。一部を更新するなら対象要素を DOM のメソッドで変更します。

HTML の解析中に document.write() がすること

コードを UTF-8 の document-write-legacy.html として保存し、ブラウザーで開きます。インラインスクリプトは HTML の解析中に実行されます。二つの引数は連結され、一つの段落として解析されます。Hello World が前後の段落の間に表示されます。改行を加える場合は document.writeln() で改行を加える仕組み を参照してください。

<!doctype html>
<html lang="ja">
<head><meta charset="utf-8"><title>document.write を試す</title></head>
<body>
  <p>スクリプトの前の段落</p>
  <script>
    document.write('<p id="written">Hello ', 'World</p>');
  </script>
  <p>スクリプトの後の段落</p>
</body>
</html>

読み込み後に既存の内容が消える理由

パーサーに挿入位置がない場合、document.write() は内部で document.open() と同様の処理を行うことがあります。そこで既存の内容が消える可能性があります。非同期スクリプトからの呼び出しが無視される場合もあり、イベント処理で常に同じ結果になるわけではありません。HTML Standard · document.write()

このメソッドは文字列を HTML として解釈し、内容を無害化しません。入力値は textContent に代入すれば、マークアップのような記号も文字として表示できます。

DOM のメソッドで出力欄だけを更新する

dom-output.html を UTF-8 で保存し、ブラウザーで開きます。表示ボタンを押すと createElement('p') で段落を作り、textContent に入力を入れます。replaceChildren(paragraph) は出力欄の子要素だけを置き換えます。DOM Standard · replaceChildren()

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>文書の一部にテキストを表示</title>
</head>
<body>
<label for="message">表示するテキスト</label>
<input id="message" value="Hello World">
<button id="show" type="button">表示</button>
<button id="clear" type="button">消去</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>

初期値では Hello World が表示されます。2 < 3 & 4 > 1 と入力すると記号もそのまま見えます。表示を何度押しても段落は一つです。消去を押すと出力だけが空になり、入力欄とボタンは残ります。