2014-01-23 81 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,你應該知道爲什麼:-)看看它單獨