javascript 文字実体参照をそのままhtml上に表示する
- 作成日 2021.12.22
- 更新日 2022.10.08
- javascript
- javascript
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 = '<>&"''
</script>
実行結果を確認すると、文字実体参照のまま表示されていることが確認できます。
「innerHTML」だと「特殊文字」のまま表示されます。
document.getElementById("hoge").innerHTML= '<>&"''
実行結果
また、以下のコードを、
document.getElementById("hoge").textContent = '<>&"''
document.getElementByIdを省略して、簡潔に記述することもできます。
hoge.textContent = '<>&"''
サンプルコード
以下は、
「実行」ボタンをクリックして、「シングルクォーテーション」を表示するサンプルコードとなります。
※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 = '<>&"''
}
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>
実行結果を確認すると、結果が表示されていることが確認できます。
-
前の記事
MySQL コタンジェントの値を求める 2021.12.22
-
次の記事
Vue.js dragleaveイベントを取得する 2021.12.22
コメントを書く