nodeValue 与 innerHTML 和 textContent.如何选择? [英] nodeValue vs innerHTML and textContent. How to choose?

查看:31
本文介绍了nodeValue 与 innerHTML 和 textContent.如何选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用纯 js 来更改标签元素的内部文本,但我不确定应该使用 innerHTML 或 nodeValue 或 textContent 的理由.我不需要创建新节点或更改 HTML 元素或任何内容——只需替换文本即可.下面是代码示例:

I'm using plain js to alter the inner text of a label element, and I wasn't sure on what grounds I should use innerHTML or nodeValue or textContent. I don't need to create a new node or change the HTML elements or anything — just replace the text. Here's an example of the code:

var myLabel = document.getElementById("#someLabel");
myLabel.innerHTML = "Some new label text!"; // this works

myLabel.firstChild.nodeValue = "Some new label text!"; // this also works.

myLabel.textContent = "Some new label text!"; // this also works.

我查看了 jQuery 源代码,它只使用了一次 nodeValue,但多次使用了 innerHTML 和 textContent.然后我发现这个 jsperf 测试表明 firstChild.nodeValue 明显更快.至少我是这么理解的.

I looked through the jQuery source, and it uses nodeValue exactly one time but innerHTML and textContent several times. Then I found this jsperf test that indicates the firstChild.nodeValue is significantly faster. At least that's what I interpret it to mean.

如果 firstChild.nodeValue 快这么多,有什么收获?它不是得到广泛支持吗?还有其他问题吗?

If firstChild.nodeValue is so much faster, what's the catch? Is it not widely supported? Is there some other issue?

推荐答案

MDN 上 textContent/innerText/innerHTML 之间的差异.

以及关于innerText/nodeValue 的Stackoverflow 答案.

总结

  1. innerHTML 将内容解析为 HTML,因此需要更长的时间.
  2. nodeValue 使用纯文本,不解析 HTML,速度更快.
  3. textContent 使用纯文本,不解析 HTML,速度更快.
  4. innerText 考虑样式.例如,它不会获得隐藏文本.
  1. innerHTML parses content as HTML, so it takes longer.
  2. nodeValue uses straight text, does not parse HTML, and is faster.
  3. textContent uses straight text, does not parse HTML, and is faster.
  4. innerText Takes styles into consideration. It won't get hidden text for instance.

innerText 根据 caniuse 但现在所有主要浏览器都支持.

innerText didn't exist in firefox until FireFox 45 according to caniuse but is now supported in all major browsers.

这篇关于nodeValue 与 innerHTML 和 textContent.如何选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆