有什么区别textContent
and innerText
在 JavaScript 中?
我可以用吗textContent
如下:
var logo$ = document.getElementsByClassName('logo')[0];
logo$.textContent = "Example";
之间的主要区别innerText
and textContent
中概述得很好Kelly Norton 的博文:innerText 与 textContent http://www.kellegous.com/j/2013/02/27/innertext-vs-textcontent/。您可以在下面找到摘要:
-
innerText
是非标准的,textContent
较早被标准化。
-
innerText
返回visible节点中包含的文本,而textContent
返回full文本。例如,在以下 HTML 中<span>Hello <span style="display: none;">World</span></span>
, innerText
将返回“Hello”,同时textContent
将返回“Hello World”。有关更完整的差异列表,请参阅以下表格:http://perfectionkills.com/the-poor-misunderstood-innerText/ http://perfectionkills.com/the-poor-misunderstood-innerText/(进一步阅读“innerText”在 IE 中有效,但在 Firefox 中无效 https://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox/1359822#1359822).
- 因此,
innerText
性能要求更高:它需要布局信息才能返回结果。
-
innerText https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText仅定义为
HTMLElement
物体,同时textContent https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent是为所有定义的Node
对象。
请务必查看此答案下面的信息丰富的评论。
textContent
在 IE8 中不可用,并且裸机 Polyfill 看起来像是使用的递归函数nodeValue
on all 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)