4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

HTML特殊文字をDOMに埋め込んでHTML表示させる方法

Last updated at Posted at 2018-09-03

いじっているシステムでこのような対応が必要だったのでその備忘録

事前知識

HTML特殊文字

HTMLタグ(< や >)を文字列として識別させたいときに&lt;などHTML特殊文字を使用します
https://html.spec.whatwg.org/multipage/syntax.html#escapingString

簡単な例
<!-- 普通のHTMLマークアップ -->
<h1>本日は晴天</h1>

<!-- HTML特殊文字 -->
&lt;h1&gt;本日は晴天&lt;/h1&gt;

実践

DOMParserでHTML特殊文字化された文字列を読み込む

const parser = new DOMParser();
const stringContainingHTMLSource = "&lt;h1&gt;本日は晴天&lt;/h1&gt;";
const doc = parser.parseFromString(stringContainingHTMLSource, "text/html");

DOMに埋め込んでHTML表示させる

DOM要素を取得して置き換え

const contents = document.getElementById("contents");
contents.innerHTML = doc.body.innerText;

ちなみにdoc.body.innerTextの出力は<h1>本日は晴天</h1>
doc.body.innerHTMLの出力は&lt;h1&gt;本日は晴天&lt;/h1&gt;となります

contents.innerHTML に doc.body.innerHTML入れようとしてハマってた...

完成形

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <div id="contents"></div>
  <script type="text/javascript" src="./index.js"></script>
</body>
</html>
index.js
const parser = new DOMParser();
const stringContainingHTMLSource = "&lt;h1&gt;本日は晴天&lt;/h1&gt;";
const doc = parser.parseFromString(stringContainingHTMLSource, "text/html");

const contents = document.getElementById("contents");
contents.innerHTML = doc.body.innerText;
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?