(Update)
: I wrote a
blog post detailing all the differences much better.
((更新)
:我写了
一篇博客文章,详细介绍了所有差异 。)
Firefox uses W3C standard Node::textContent
, but its behavior differs "slightly" from that of MSHTML's proprietary innerText
(copied by Opera as well, some time ago, among dozens of other MSHTML features).
(Firefox使用W3C标准的Node::textContent
,但是其行为与MSHTML的专有innerText
(在一段时间之前由Opera复制,还有许多其他MSHTML功能)“稍有不同”。)
First of all, textContent
whitespace representation is different from innerText
one.
(首先, textContent
空格表示与innerText
不同。)
Second, and more importantly, textContent
includes all of SCRIPT tag contents , whereas innerText doesn't.(其次,更重要的是, textContent
包含所有SCRIPT标签内容 ,而innerText不包含。)
Just to make things more entertaining, Opera - besides implementing standard textContent
- decided to also add MSHTML's innerText
but changed it to act as textContent
- ie including SCRIPT contents (in fact, textContent
and innerText
in Opera seem to produce identical results, probably being just aliased to each other).
(为了使事情更具娱乐性,Opera除了实现标准的textContent
之外,还决定添加MSHTML的innerText
但将其更改为textContent
,即包括SCRIPT内容(实际上,Opera中的textContent
和innerText
似乎产生相同的结果,可能只是彼此混叠)。)
textContent
is part of Node
interface, whereas innerText
is part of HTMLElement
.
(textContent
是Node
接口的一部分,而innerText
是HTMLElement
一部分。)
This, for example, means that you can "retrieve" textContent
but not innerText
from text nodes:(例如,这意味着您可以从文本节点“检索” textContent
而不是“ innerText
”:)
var el = document.createElement('p');
var textNode = document.createTextNode('x');
el.textContent; // ""
el.innerText; // ""
textNode.textContent; // "x"
textNode.innerText; // undefined
Finally, Safari 2.x also has buggy innerText
implementation.
(最后,Safari 2.x还具有错误的innerText
实现。)
In Safari, innerText
functions properly only if an element is neither hidden (via style.display == "none"
) nor orphaned from the document.(在Safari中,仅当元素既没有隐藏(通过style.display == "none"
)也没有从文档中孤立出来时, innerText
才能正常运行。)
Otherwise, innerText
results in an empty string.(否则, innerText
导致一个空字符串。)
I was playing with textContent
abstraction (to work around these deficiencies), but it turned out to be rather complex .
(我正在玩textContent
抽象(以解决这些缺陷),但事实证明它相当复杂 。)
You best bet is to first define your exact requirements and follow from there.
(最好的选择是首先定义您的确切要求,然后从那里开始。)
It is often possible to simply strip tags off of innerHTML
of an element, rather than deal with all of the possible textContent
/ innerText
deviations.(通常可以简单地从元素的innerHTML
中剥离标签,而不是处理所有可能的textContent
/ innerText
偏差。)
Another possibility, of course, is to walk the DOM tree and collect text nodes recursively.
(当然,另一种可能性是遍历DOM树并递归收集文本节点。)