textContent与innerText之间的区别 [英] Difference between textContent vs innerText

查看:125
本文介绍了textContent与innerText之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中 textContent innerText 有什么区别?

What is the difference between textContent and innerText in JavaScript?

我可以使用 textContent ,如下所示:

Can I use textContent as follows:

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


推荐答案

其他答案都没有成功提供完整说明因此这个。 <$ href =http://www.kellegous中概述了 innerText textContent 之间的主要区别。 .com / j / 2013/02/27 / innertext-vs-textcontent /rel =noreferrer> Kelly Norton的博文:innerText与textContent 。您可以在下面找到摘要:

None of the other answers succeeds in providing the full explanation, hence this one. The key differences between innerText and textContent are outlined very well in Kelly Norton's blogpost: innerText vs. textContent. Below you can find a summary:


  1. innerText 是非标准的,而 textContent 之前已标准化。

  2. innerText 返回可见包含在节点中的文本,而 textContent 返回完整文本。例如,在以下HTML < span> Hello< span style =display:none;> World< / span>< / span> innerText 将返回'Hello',而 textContent 将返回'Hello World'。有关更完整的差异列表,请参阅 http://perfectionkills.com/the-上的表格。差错误 - innerText /

  3. 因此, innerText 的性能要高得多:它需要布局返回结果的信息。

  1. innerText was non-standard, while textContent was standardized earlier.
  2. innerText returns the visible text contained in a node, while textContent returns the full text. For example, on the following HTML <span>Hello <span style="display: none;">World</span></span>, innerText will return 'Hello', while textContent will return 'Hello World'. For a more complete list of differences, see the table at http://perfectionkills.com/the-poor-misunderstood-innerText/.
  3. As a result, innerText is much more performance-heavy: it requires layout information to return the result.

IE8中的 textContent 的解决方法涉及在指定节点的所有 childNodes 上使用 nodeValue 的递归函数,这里是对polyfill的尝试:

A workaround for textContent in IE8- would involve a recursive function using nodeValue on all childNodes of the specified node, here's a try at a polyfill:

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;
}

这篇关于textContent与innerText之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆