有两个问题可以初步理解二者的区别:
- 结点原生的文本内容是什么?(What is the raw textual content inside of these Nodes?)
- 展示给用户的文本是什么?(What is the text being presented to the user?)
textContet 表示前者,innerText 表示后者。
1. innerText 不能取到没有渲染在页面上的文本
<div id="t">
<div>
lions, tigers<div style="visibility: hidden"> and bears</div>
</div>
</div>
复制代码
从上面这段 HTML 中取值可以理解这种区别。
- innerText:
"lions, tigers"
- textContent:
"lions,\ntigers and bears"
innerText 更像是直接从渲染的页面上拷贝的值,而 textContent 是结点在代码中的值。
innerText is that it is roughly what you would get if you selected the text and copied.
textContent is just a concatenation of the values of all TextNodes in the sub-tree.
2. innerText 会带来性能影响
由于 innerText 的值依赖渲染之后的结果,会收到 CSS 样式的影响,因此它会触发重排(reflow),所以使用它会有一定的性能影响;而 textContent 不会。
因此更建议使用 textContent。
3. innerText 不是标准制定出来的 api
innerText 是 IE 引入的,在 IE 那个时代被广泛使用起来的。