javascript 文字実体参照をそのままhtml上に表示する

javascript 文字実体参照をそのままhtml上に表示する

javascriptで、文字実体参照をそのままhtml上に表示するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 106.0.5249.103

文字実体参照をそのままhtml上に表示

文字実体参照(エンティティ参照)をそのままhtml上に表示するには、「textContent」を使用します。

<h1 id="bar"></h1>

<script>

'use strict';

document.getElementById("hoge").textContent = '&lt;&gt;&amp;&quot;&#39;'

</script>

実行結果を確認すると、文字実体参照のまま表示されていることが確認できます。

「innerHTML」だと「特殊文字」のまま表示されます。

document.getElementById("hoge").innerHTML= '&lt;&gt;&amp;&quot;&#39;'

実行結果

また、以下のコードを、

document.getElementById("hoge").textContent = '&lt;&gt;&amp;&quot;&#39;'

document.getElementByIdを省略して、簡潔に記述することもできます。

hoge.textContent = '&lt;&gt;&amp;&quot;&#39;'

サンプルコード

以下は、
「実行」ボタンをクリックして、「シングルクォーテーション」を表示するサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>  

  const hoge = () => {

    bar.textContent = '&lt;&gt;&amp;&quot;&#39;'

  }

  window.onload = () => {

    btn.onclick = () => { hoge() }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-1/3 px-4">

    <div id="sample" class="flex flex-col justify-center">
      
      <h1 id="foo" class="font-semibold text-purple-500 text-lg mr-auto">実行結果</h1>

      <h1 id="bar" class="font-semibold text-gray-500 text-lg mr-auto"></h1>

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-purple-300 text-purple-700 font-semibold hover:text-white py-2 px-4 border border-purple-300 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、結果が表示されていることが確認できます。