0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

DOMParserを使って文字列からイベント処理付きのDOMを生成する

0
Posted at

DOMParserとは

DOMParserは文字列から DOM の Document に解釈する機能を提供します
これを利用することでcreateElementを利用せず構造化されたHTMLをJavaScriptから生成できます。
イベント処理も付与も可能ですので、そのテクニックについて記載しています。

実装

// DOMParserを初期化
const parser = new DOMParser();
const htmlString = '<div><span class="color-red">Click Meeee!</span></div>';

// domを生成してイベントを設定
const dom = parser.parseFromString(htmlString, 'text/html');
const firstChild = dom.body.firstChild;
firstChild.addEventListener('click', () => { console.log('click') });

// レンダリング(id="content"を持つ要素に挿入)
const container = document.querySelector('#content');
container.prepend(firstChild);

createElementを多用する機会があれば、この方法で明示的にHTML構造を記載できるので、ソースコードの可読性が良くなると思います。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?