Node:insertBefore() 方法

Baseline 已廣泛支援

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

insertBefore() 方法是 Node 介面的一部分,用於將一個節點插入到指定父節點參考節點之前,作為其子節點。

如果給定的節點已存在於文件中,insertBefore() 會將其從當前位置移動到新位置。(即,在將其新增到指定的父節點之前,它將自動從其現有父節點中移除。)

這意味著一個節點不能同時存在於文件的兩個位置。

注意: Node.cloneNode() 可用於在將節點新增到新父節點之前建立其副本。請注意,使用 cloneNode() 建立的副本不會自動保持同步。

如果給定的子節點是 DocumentFragment,則 DocumentFragment 的所有內容都會被移動到指定父節點的子節點列表中。

語法

js
insertBefore(newNode, referenceNode)

引數

newNode

要插入的節點。

referenceNode

newNode 插入到其之前的節點。如果此值為 null,則 newNode 將插入到節點的子節點列表的末尾。

注意: referenceNode **不是**可選引數。您必須顯式傳遞一個 Nodenull。未提供或傳入無效值可能會在不同瀏覽器版本中表現 不同

返回值

返回新增的子節點(除非 newNodeDocumentFragment,在這種情況下,將返回空的 DocumentFragment)。

異常

插入前的有效性檢查

示例

示例 1

html
<div id="parentElement">
  <span id="childElement">foo bar</span>
</div>
js
// Create the new node to insert
const newNode = document.createElement("span");

// Get a reference to the parent node
const parentDiv = document.getElementById("childElement").parentNode;

// Begin test case [ 1 ] : Existing childElement (all works correctly)
let sp2 = document.getElementById("childElement");
parentDiv.insertBefore(newNode, sp2);
// End test case [ 1 ]

// Begin test case [ 2 ] : childElement is of Type undefined
sp2 = undefined; // Non-existent node of id "childElement"
parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node
// End test case [ 2 ]

// Begin test case [ 3 ] : childElement is of Type "undefined" (string)
sp2 = "undefined"; // Non-existent node of id "childElement"
parentDiv.insertBefore(newNode, sp2); // Generates "Type Error: Invalid Argument"
// End test case [ 3 ]

示例 2

html
<div id="parentElement">
  <span id="childElement">foo bar</span>
</div>
js
// Create a new, plain <span> element
const sp1 = document.createElement("span");

// Get the reference element
const sp2 = document.getElementById("childElement");
// Get the parent element
const parentDiv = sp2.parentNode;

// Insert the new element into before sp2
parentDiv.insertBefore(sp1, sp2);

注意: 沒有 insertAfter() 方法。可以透過結合使用 insertBefore 方法和 Node.nextSibling 來模擬。

在前面的示例中,可以使用以下方法將 sp1 插入到 sp2 之後:

js
parentDiv.insertBefore(sp1, sp2.nextSibling);

如果 sp2 沒有下一個兄弟節點,則它必須是最後一個子節點 — sp2.nextSibling 返回 nullsp1 會被插入到子節點列表的末尾(緊跟在 sp2 之後)。

示例 3

使用 firstChild 屬性,將元素插入到第一個子元素之前。

js
// Get the parent element
const parentElement = document.getElementById("parentElement");
// Get the parent's first child
const theFirstChild = parentElement.firstChild;

// Create a new element
const newElement = document.createElement("div");

// Insert the new element before the first child
parentElement.insertBefore(newElement, theFirstChild);

當元素沒有第一個子節點時,firstChildnull。元素仍將被新增到父節點,位於最後一個子節點之後。

由於父元素沒有第一個子節點,因此也沒有最後一個子節點。因此,新插入的元素是唯一的元素。

規範

規範
DOM
# dom-node-insertbefore

瀏覽器相容性

另見