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

查看:184
本文介绍了nodeValue vs 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. nodeValue

  2. innerHTML 以HTML格式解析内容,花费更长时间。

  3. textContent 使用直线文本,不解析HTML,而且速度更快。

  4. innerText 考虑样式。它不会被隐藏文本。

  1. nodeValue is a little more confusing to use, but faster than innerHTML.
  2. innerHTML parses content as HTML and takes longer.
  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 没有存在于firefox中,直到FireFox 45根据 caniuse ,但现在支持所有主流浏览器。

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

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

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