textContentとinnerTextの違い 質問する

textContentとinnerTextの違い 質問する

JavaScript のtextContentとの違いは何ですか?innerText

textContent以下のように使えますか?

var logo$ = document.getElementsByClassName('logo')[0];
logo$.textContent = "Example";

ベストアンサー1

innerTextとの主な違いはtextContentKelly Norton のブログ投稿: innerText と textContent以下に概要を示します。

  1. innerText非標準でしたが、textContent以前に標準化されました。
  2. innerTextはノードに含まれる可視テキストを返し、 は全文textContentを返します。たとえば、次の HTML では、は「Hello」を返し、 は「Hello World」を返します。より完全な相違点の一覧については、次の表を参照してください。<span>Hello <span style="display: none;">World</span></span>innerTexttextContenthttp://perfectionkills.com/the-poor-misunderstood-innerText/(詳しくは「innerText」はIEでは動作しますが、Firefoxでは動作しません)。
  3. その結果、innerTextパフォーマンスが大幅に低下します。結果を返すにはレイアウト情報が必要になります。
  4. innerTextHTMLElementはオブジェクトに対してのみ定義されますが、textContentすべてのオブジェクトに対して定義されますNode

この回答の下にある有益なコメントも必ずご覧ください。

textContentIE8 では利用できず、ベアメタル ポリフィルは指定されたすべてのノードnodeValueでを使用する再帰関数のように見えました。childNodes

function textContent(rootNode) {
  if ('textContent' in document.createTextNode(''))
    return rootNode.textContent;

  var childNodes = rootNode.childNodes,
      len = childNodes.length,
      result = '';
  
  for (var i = 0; i < len; i++) {
    if (childNodes[i].nodeType === 3)
      result += childNodes[i].nodeValue;
    else if (childNodes[i].nodeType === 1) 
      result += textContent(childNodes[i]);
  }

  return result;
}

おすすめ記事