Text: wholeText 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Text 介面的只讀 wholeText 屬性返回與該節點在邏輯上相鄰的所有 Text 節點的全部文字。文字按照文件順序連線。這允許指定任何文字節點並以單個字串形式獲取所有相鄰的文字。

注意: 這類似於呼叫 Node.normalize() 然後讀取文字值,但不會修改樹。

一個包含連線文字的字串。

示例

假設你的網頁中有以下簡單的段落

html
<p>
  Through-hiking is great!
  <strong>No insipid election coverage!</strong> However,
  <a href="https://en.wikipedia.org/wiki/Absentee_ballot">casting a ballot</a>
  is tricky.
</p>

你決定不喜歡中間的句子,所以你刪除了它

js
const paragraph = document.querySelector("p"); // Reads the paragraph
paragraph.removeChild(paragraph.childNodes[1]); // Delete the strong element

現在你得到了 “長途徒步很棒!但是,投票是棘手的。”,在超連結之前有兩個節點

  1. 一個包含字串 “長途徒步很棒!”Text 節點
  2. 第二個 Text 節點包含字串 “ 但是,”

要一次獲取這兩個節點,你可以呼叫 paragraph.childNodes[0].wholeText

js
console.log(`'${paragraph.childNodes[0].wholeText}'`); // 'Through-hiking is great!   However, '

規範

規範
DOM
# ref-for-dom-text-wholetext①

瀏覽器相容性

另見

  • 它所屬的 Text 介面。