LoginSignup
38
29

More than 5 years have passed since last update.

HTML文字列をElementに変換する

Posted at
  • document.createElementで適当なElementを作成し、innerHTMLでHTMLの文字列を設定する。
  • 差し込んだHTMLがfirstElementChildElementとして取得できる。
createElementFromHTML
/**
 * HTML文字列をElementへ変換する。
 * @param html HTML文字列
 * @returns {Element} 
 */
function createElementFromHTML(html) {
    const tempEl = document.createElement('div');
    tempEl.innerHTML = html;
    return tempEl.firstElementChild;
}

// 呼び出し例
createElementFromHTML('<div style="width: 300px;"></div>');
38
29
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
38
29