HTMLElement: innerText 屬性

Baseline 已廣泛支援

此特性已經非常成熟,並且適用於許多裝置和瀏覽器版本。自 2016 年 3 月以來,它已在所有瀏覽器中可用。

HTMLElement 介面的 innerText 屬性表示一個節點及其後代的可渲染文字內容。

作為 getter 時,它近似地返回使用者透過滑鼠選中元素內容並複製到剪貼簿後獲得文字。作為 setter 時,它將用給定的值替換元素的所有子節點,並將任何換行符轉換為 <br> 元素。

注意: innerText 很容易與 Node.textContent 混淆,但兩者之間存在重要區別。基本上,innerText 考慮文字的可渲染外觀,而 textContent 則不考慮。

一個表示元素可渲染文字內容的字串。

如果元素本身未被 渲染(例如,已從文件中分離或對使用者不可見),則返回值與 Node.textContent 屬性相同。

警告: 在節點上設定 innerText 會刪除該節點所有的子節點,並用一個具有給定字串值的文字節點替換它們。

示例

此示例將 innerTextNode.textContent 進行比較。請注意 innerText 如何考慮 <br> 元素等內容,並忽略隱藏的元素。

HTML

html
<h3>Source element:</h3>
<p id="source">
  <style>
    #source {
      color: red;
    }
    #text {
      text-transform: uppercase;
    }
  </style>
  <span id="text">
    Take a look at<br />
    how this text<br />
    is interpreted below.
  </span>
  <span style="display:none">HIDDEN TEXT</span>
</p>
<h3>Result of textContent:</h3>
<textarea id="textContentOutput" rows="6" cols="30" readonly>…</textarea>
<h3>Result of innerText:</h3>
<textarea id="innerTextOutput" rows="6" cols="30" readonly>…</textarea>

JavaScript

js
const source = document.getElementById("source");
const textContentOutput = document.getElementById("textContentOutput");
const innerTextOutput = document.getElementById("innerTextOutput");

textContentOutput.value = source.textContent;
innerTextOutput.value = source.innerText;

結果

規範

規範
HTML
# the-innertext-idl-attribute

瀏覽器相容性

另見