2014-01-23 110 views
72

我使用普通的js来改变标签元素的内部文本,我不确定我应该使用innerHTML还是nodeValue或textContent。我不需要创建新节点或更改HTML元素或任何东西 - 只需替换文本即可。下面的代码示例:nodeValue vs innerHTML和textContent。如何选择?

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显着更快。至少这就是我所理解的意思。

如果firstChild.nodeValue快得多,那有什么用?它是否得到广泛支持?还有其他问题吗?

回答

83

Differences between textContent/innerText/innerHTML on MDN.

And a Stackoverflow answer about innerText/nodeValue.

摘要

  1. 的nodeValue更多的是有点混乱使用,但比innerHTML的速度更快。
  2. innerHTML将内容解析为HTML并需要更长的时间。
  3. textContent使用直接文本,不解析HTML,速度更快。
  4. innerText注意风格。例如它不会得到隐藏文字。

innerText没有在Firefox根据caniuse存在,直到火狐45,但现在所有主流浏览器的支持。

+8

您能否添加摘要?有时链接会被破坏,有时会导致更多的信息而不是相关的信息。 – Panzercrisis

+0

呃,'nodeValue'不能解析HTML – Bergi

+0

“使用textContent可以防止XSS攻击”https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent – DRP

39

.textContent输出text/plain.innerHTML输出text/html

快速例如:

var example = document.getElementById('exampleId');

example.textContent = '<a href="https://google.com">google</a>';

输出:< A HREF = “http://google.com” >谷歌< /一个>

example.innerHTML = '<a href="https://google.com">google</a>';

输出:google

从第一个示例中可以看出,text/plain类型的输出未被浏览器解析并导致显示完整内容。类型text/html的输出告诉浏览器在显示它之前解析它。

MDN innerHTMLMDN textContentMDN nodeValue

4

两个我清楚地知道,并与合作是innerHTML的和的textContent

我用的textContent时,我只是想改变一个段落的文字或标题,像这样:

var heading = document.getElementById('heading') 
 
var paragraph = document.getElementById('paragraph') 
 

 
setTimeout(function() { 
 
    heading.textContent = 'My New Title!' 
 
    paragraph.textContent = 'My second <em>six word</em> story.' 
 
}, 2000)
em { font-style: italic; }
<h1 id="heading">My Title</h1> 
 
<p id="paragraph">My six word story right here.</p>

所以,的textContent只是改变了文本,但它不会解析HTML,因为我们可以从结果中的纯文本中可见的标记告诉它。

如果我们要解析HTML,我们用innerHTML的这样的:

var heading = document.getElementById('heading') 
 
var paragraph = document.getElementById('paragraph') 
 

 
setTimeout(function() { 
 
    heading.innerHTML = 'My <em>New</em> Title!' 
 
    paragraph.innerHTML = 'My second <em>six word</em> story.' 
 
}, 2000)
em { font-style: italic; }
<h1 id="heading">My Title</h1> 
 
<p id="paragraph">My six word story right here.</p>

所以,这第二个示例解析我分配给DOM元素的的innerHTML属性字符串作为HTML。

这是真棒,和一个大的安全漏洞:)

(查找XSS,如果你想了解安全性这一点)

0

的innerText大致是,如果你选择,你会得到什么文本并复制它。 innerText中不存在的元素不存在。

的textContent所有 TextNodes在子树的值的串联。无论是否呈现。

这里是一个great post详细

的innerHTML不应该包括在的innerText或的textContent比较的差异,因为它是完全diffreent,你应该知道为什么:-)看看它单独