innerText 和 textContent 的区别?

有两个问题可以初步理解二者的区别:

  • 结点原生的文本内容是什么?(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 那个时代被广泛使用起来的。

参考

  1. 《INNERTEXT VS. TEXTCONTENT》

转载于:https://juejin.im/post/5c0914c5f265da610e7fe372

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值