问题描述
我正在使用纯 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 答案.
总结
- innerHTML 将内容解析为 HTML,因此需要更长的时间.
- nodeValue 使用纯文本,不解析 HTML,速度更快.
- textContent 使用纯文本,不解析 HTML,速度更快.
- innerText 考虑样式.例如,它不会获得隐藏文本.
- innerHTML parses content as HTML, so it takes longer.
- nodeValue uses straight text, does not parse HTML, and is faster.
- textContent uses straight text, does not parse HTML, and is faster.
- 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.如何选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!