🍃このブログは移転しました。
3秒後、自動的に移動します・・・。

innerTextとtextContentの違い

いきなりなんのこっちゃですが。
これは意外に実用的な知識な気がしてきた。

そもそもは、DOMのセレクタ達のパフォーマンスが気になって以下のようなてきとーなサンプルを作ってたとき。
ふと、結果をDOMに落とす時に、どう書くのが良いんやろ?って思ったのがきっかけ。

似てるようで全然違った

どちらもNodeからテキストを得るっちゃ得るけども。
困ったときのMDN!

参考:Node.textContent - Web API reference | MDN

違いそのいち

Note that while textContent gets the content of all elements, including script and style elements, the mostly equivalent IE-specific property, innerText, does not.

対象がscriptタグやらstyleタグやったりすると、innerTextでは中身が取得できない。
・・・手元のChromeやとできたので、IEだけなんかな?

違いそのに

innerText is also aware of style and will not return the text of hidden elements, whereas textContent will.

visibilty: hiddenとか、改行コードのそれとか、DOMには存在するけどレンダリングされた時に見えてないものは、innerTextでは取得できない。

違いそのさん

As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.

innerTextで書き換えるとリフローが発生するけど、textContentだと発生しない。
これはデカい違いなのではなかろうか。

参考:kelly norton: innerText vs. textContent

ここ見るのがいちばんわかりやすかったです。