ドキュメントにHTMLを表す文字列を書き込む(write)

Document オブジェクトの write メソッドを使用するとドキュメントに対して文字列を書き込むことができます。文字列は HTML として解釈されます。 なお Document.write メソッドは現在でも利用可能ですが、利用の推奨はされていません。ここでは Document.write メソッドの使い方について解説します。

(Last modified: )

ドキュメントに文字列を書き込む

Document オブジェクトの write メソッドは、ドキュメントに対して文字列を書き込みます。書式は次のとおりです。

document.write(string)

引数に指定した文字列をドキュメントに対して書き込みます。書き込まれた文字列は HTML コードとして扱われます。

次のサンプルをみてください。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプル</title>
</head>
<body>

<script>
document.write('<p>Hello</p>');
</script>

</body>
</html>

document.write メソッドを使って <p> タグを書き込んでいます。この HTML ページをブラウザで表示すると次のように表示されます。

ドキュメントに文字列を書き込む(1)

<script> 要素の下に <p>Hello</p> が書き込まれていることが確認できます。

このように簡単にドキュメントに対して文字列の形式で HTML コードを書き込むことができますが、現在 HTML に関する仕様を定めている HTML Living standard ではこのメソッドの使用について推奨はしていません。

8.4.3 document.write()

This method has very idiosyncratic behavior. In some cases, this method can affect the state of the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document (e.g. if the string written is the string "<plaintext>" or "<!--"). In other cases, the call can clear the current page first, as if document.open() had been called. In yet more cases, the method is simply ignored, or throws an exception. Users agents are explicitly allowed to avoid executing script elements inserted via this method. And to make matters even worse, the exact behavior of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use of this method is strongly discouraged.

現在利用が推奨されていない Document.write メソッドの代わりにドキュメントに対してテキストを書き込むための方法のひとつとして Document.currentScript プロパティと insertAdjacentHTML メソッドを組み合わせて代替することができます。詳しくは「現在処理を実行しているscript要素を取得(currentScript)」を参照されてください。

サンプルコード

次のサンプルを見てください。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプル</title>
</head>
<body>

<script>
document.write('<ul><li>Orange</li><li>Lemon</li></ul>');
</script>

</body>
</html>

この HTML ページをブラウザで表示すると、 document.write メソッドの引数に文字列で指定した ul タグや li タグがドキュメントに書き込まれています。

ドキュメントに文字列を書き込む(2)

-- --

Document.write メソッドの使い方について解説しました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。