【前端學習】innerText 與 textContent 的差異


Posted by Annie-Chien on 2022-08-21

innerText 和 textContent 好像都可以用來取得元素內的文字,那我到底該用哪一個? 還是其實都沒差(才怪!)。


MDN 的定義

先來看看 MDN 是如何解釋的:

innerText

The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants.

textContent

The textContent property of the Node interface represents the text content of the node and its descendants.

英文定義看起來還是沒什麼兩樣啊...
幫你畫個重點:兩個都是用來代表 text content (文字內容)沒錯,不過眼尖的你應該有發現 innerText 代表的不單單只是純文字內容,而是 rendered text content(渲染後的文字內容)。

實際測試

首先我們有個 h1 內寫上 Hello world 的文字內容。

<h1 id='test1'>Hello, world</h1>

css 設定text-transform,讓文字內容以全大寫的樣式渲染在畫面上。

#test1{
  text-transform: uppercase;
}

那猜猜看以下的 JS 會印出什麼呢?

const textContent1 = document.querySelector('#test1').textContent;
const innerText1 = document.querySelector('#test1').innerText;

console.log('textContent: ' + textContent1)
console.log('innerText: ' + innerText1)

. . .

答案如下:

  • textContent 會是最初在 html 內打的文字內容
  • innerText 則是實際出現在畫面上全大寫的文字內容

牛刀小試

了解它們的差別後,相信你一定很快就知道以下程式碼的 textContent 和 innerText 分別是什麼了吧😉

<h1 id='test2'>JavaScript <br/>is fun</h1>

附上 codepen 的測試,自己玩玩去找答案吧!

總結

快速用一句話來總結:

textContet 回傳純文字,而 innerText 則會回傳實際呈現在頁面上的樣子。


#javascript







Related Posts

What is Azure Release Pipeline

What is Azure Release Pipeline

DAY2:String ends with?

DAY2:String ends with?

Day 136

Day 136


Comments