vote life iconVote Life: /

DevNotes - JavaScript

innerHTML, outerHTML 要素内のHTMLを取得

2022-04-11

Element.innerHTML - Web API | MDN

Element.outerHTML - Web API | MDN

構文

innerHTML は要素内のHTMLを取得。
content = element.innerHTML; // 取得
element.innerHTML = content; // 設定

outerHTML は要素自身も含めてHTMLを取得。
content = element.outerHTML; // 取得
element.outerHTML = content; // 設定

html (before)

<div id="inner"><span>innerBefore</span></div> <div id="outer"><span>outerBefore</span></div>

js

var inner = document.getElementById("inner").innerHTML; console.log(inner); // "<span>innerBefore</span>" document.getElementById("inner").innerHTML = "innerAfter"; inner = document.getElementById("inner").innerHTML; console.log(inner); // "innerAfter" var outer = document.getElementById("outer").outerHTML; console.log(outer); // "<div id="outer"><span>outerBefore</span></div>" document.getElementById("outer").outerHTML = "<div id="outer">outerAfter</div>"; outer = document.getElementById("outer").outerHTML; console.log(outer); // "<div id="outer">outerAfter</div>"

html (after)

<div id="inner">innerAfter</div> <div id="outer">outerAfter</div>