網站搜尋

javascript - nodeValue 與 innerHTML 和 textContent。如何選擇?


我正在使用純 JavaScript 來更改標籤元素的內部文字,我不確定應該根據什麼情況使用 innerHTML、nodeValue 還是 textContent。我不需要創建新節點或更改 HTML 元素之類的——只是替換文字而已。這裡有一個程式碼範例:

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 這麼快,那有什麼問題呢?它是不是不被廣泛支持?還是有其他問題?

答案#1

MDN 上 textContent/innerText/innerHTML 的差異。

以及關於 innerText/nodeValue 的 Stackoverflow 答覆。

摘要

  1. innerHTML 將內容解析為 HTML,因此需要更長時間。
  2. nodeValue 使用純文字,不解析 HTML,且速度較快。
  3. textContent 使用純文字,不解析 HTML,且速度較快。
  4. innerText 會考慮樣式。例如,它不會取得隱藏的文字。

根據 caniuse,innerText 在 Firefox 直到 FireFox 45 才存在,但現在所有主要瀏覽器都已支援。

答案#2

.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">google</a>

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

輸出:Google

從第一個例子可以看到,text/plain 類型的輸出不會被瀏覽器解析,結果是完整內容直接顯示出來。text/html 類型的輸出則告訴瀏覽器在顯示之前先解析它。

MDN innerHTML、MDN textContent、MDN nodeValue