问题描述
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:
-
innerText
是非标准的,而textContent
之前已标准化。 -
innerText
返回可见包含在节点中的文本,而textContent
返回完整文本。例如,在以下HTML< span> Hello< span style =display:none;> World< / span>< / span>
,innerText
将返回'Hello',而textContent
将返回'Hello World'。有关更完整的差异列表,请参阅。 - 因此,
innerText
的性能要高得多:它需要布局返回结果的信息。
innerText
was non-standard, whiletextContent
was standardized earlier.innerText
returns the visible text contained in a node, whiletextContent
returns the full text. For example, on the following HTML<span>Hello <span style="display: none;">World</span></span>
,innerText
will return 'Hello', whiletextContent
will return 'Hello World'. For a more complete list of differences, see the table at http://perfectionkills.com/the-poor-misunderstood-innerText/.- 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之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!