DocumentFragment

Baseline 廣泛可用 *

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

* 此特性的某些部分可能存在不同級別的支援。

DocumentFragment 介面表示一個最小的文件物件,它沒有父節點。

它被用作一個輕量級的 Document 版本,用於儲存一個由節點組成的文件結構片段,就像標準的文件一樣。關鍵區別在於文件片段不屬於活動文件樹結構。對片段所做的更改不會影響文件。

EventTarget Node DocumentFragment

建構函式

DocumentFragment()

建立並返回一個新的 DocumentFragment 物件。

例項屬性

此介面沒有特定屬性,但繼承了其父介面 Node 的屬性。

DocumentFragment.childElementCount 只讀

返回 DocumentFragment 中子 元素 的數量。

DocumentFragment.children 只讀

返回一個包含 DocumentFragment 物件的所有型別為 Element 的子節點的即時 HTMLCollection

DocumentFragment.firstElementChild 只讀

返回 DocumentFragment 物件的第一個子 Element,如果沒有則返回 null

DocumentFragment.lastElementChild 只讀

返回 DocumentFragment 物件的最後一個子 Element,如果沒有則返回 null

例項方法

此介面繼承了其父介面 Node 的方法。

DocumentFragment.append()

在文件片段的最後一個子節點之後插入一組 Node 物件或字串。

DocumentFragment.prepend()

在文件片段的第一個子節點之前插入一組 Node 物件或字串。

DocumentFragment.querySelector()

在文件片段中,按文件順序查詢與指定選擇器匹配的第一個 Element 節點。

DocumentFragment.querySelectorAll()

在文件片段中,查詢與指定選擇器匹配的所有 Element 節點,並返回一個 NodeList

DocumentFragment.moveBefore()

將給定的 Node 作為直接子節點移動到呼叫它的 DocumentFragment 中,位於給定的參考節點之前,而無需先移除再插入該節點。

DocumentFragment.replaceChildren()

用指定的新子節點集替換 DocumentFragment 中現有的子節點。

DocumentFragment.getElementById()

在文件片段中,按文件順序查詢與指定 ID 匹配的第一個 Element 節點。功能上等同於 Document.getElementById()

用法說明

DocumentFragment 的一個常見用途是建立一個片段,在其內部組裝一個 DOM 子樹,然後使用 Node 介面方法(如 appendChild()append()insertBefore())將該片段追加或插入到 DOM 中。這樣做會將片段的節點移入 DOM,留下一個空的 DocumentFragment

此介面對於 Web Components 也非常有用:<template> 元素在其 HTMLTemplateElement.content 屬性中包含一個 DocumentFragment

可以使用 document.createDocumentFragment() 方法或建構函式建立一個空的 DocumentFragment

效能

DocumentFragment 的效能優勢常常被誇大。事實上,在某些引擎中,使用 DocumentFragment 比在迴圈中直接追加到文件中更慢,正如此基準測試所示。然而,這些示例之間的差異如此微小,以至於最好最佳化可讀性而不是效能。

示例

HTML

html
<ul></ul>

JavaScript

js
const ul = document.querySelector("ul");
const fruits = ["Apple", "Orange", "Banana", "Melon"];

const fragment = new DocumentFragment();

for (const fruit of fruits) {
  const li = document.createElement("li");
  li.textContent = fruit;
  fragment.append(li);
}

ul.append(fragment);

結果

規範

規範
DOM
# interface-documentfragment

瀏覽器相容性