Element: replaceChildren() 方法
Element.replaceChildren() 方法使用指定的子節點集替換 Node 的現有子節點。這些子節點可以是字串或 Node 物件。
語法
js
replaceChildren(param1)
replaceChildren(param1, param2)
replaceChildren(param1, param2, /* …, */ paramN)
引數
param1, …,paramN-
一組要替換
Element現有子節點的Node物件或字串。如果未指定任何替換物件,則Element將清空所有子節點。
返回值
無(undefined)。
異常
HierarchyRequestErrorDOMException-
當違反 節點樹的約束 時丟擲。
示例
清空節點
replaceChildren() 提供了一種非常方便的機制來清空節點的所有子節點。您可以在父節點上呼叫它,而不指定任何引數
js
myNode.replaceChildren();
在元素之間轉移節點
replaceChildren() 使您能夠輕鬆地在元素之間轉移節點,而無需進行冗長的迴圈程式碼。例如,假設我們有一個簡單的應用程式,允許您選擇派對想要吃的食物。HTML 可能看起來像這樣
html
<h2>Party food option list</h2>
<main>
<div>
<label for="no">No thanks!</label>
<select id="no" multiple size="10">
<option>Apples</option>
<option>Oranges</option>
<option>Grapes</option>
<option>Bananas</option>
<option>Kiwi fruits</option>
<option>Chocolate cookies</option>
<option>Peanut cookies</option>
<option>Chocolate bars</option>
<option>Ham Sandwiches</option>
<option>Cheese Sandwiches</option>
<option>Falafel sandwiches</option>
<option>Ice cream</option>
<option>Jelly</option>
<option>Carrot sticks and hummus</option>
<option>Margherita pizza</option>
<option>Pepperoni pizza</option>
<option>Vegan veggie pizza</option>
</select>
</div>
<div class="buttons">
<button id="to-yes">Transfer to "Yes" --></button>
<button id="to-no"><-- Transfer to "No"</button>
</div>
<div>
<label for="yes">Yes please!</label>
<select id="yes" multiple size="10"></select>
</div>
</main>
為了便於檢視,可以設定一些簡單的 CSS,將兩個選擇列表並排放置,並將控制按鈕放在它們之間
css
main {
display: flex;
}
div {
margin-right: 20px;
}
label,
button {
display: block;
}
.buttons {
display: flex;
flex-flow: column;
justify-content: center;
}
select {
width: 200px;
}
當我們按下“是”按鈕時,我們將“否”列表中的任何選定選項轉移到“是”列表中;當我們按下“否”按鈕時,我們將“是”列表中的任何選定選項轉移到“否”列表中。
為了實現這一點,我們為每個按鈕都設定了一個點選事件處理程式。該處理程式在一個常量中收集要轉移的選定選項,在另一個常量中收集要轉移到的列表中的現有選項。然後,它在要轉移選項的列表上呼叫 replaceChildren(),並使用展開運算子將兩個常量中包含的所有選項作為引數傳遞。
js
const noSelect = document.getElementById("no");
const yesSelect = document.getElementById("yes");
const noBtn = document.getElementById("to-no");
const yesBtn = document.getElementById("to-yes");
yesBtn.addEventListener("click", () => {
const selectedTransferOptions =
document.querySelectorAll("#no option:checked");
const existingYesOptions = document.querySelectorAll("#yes option");
yesSelect.replaceChildren(...selectedTransferOptions, ...existingYesOptions);
});
noBtn.addEventListener("click", () => {
const selectedTransferOptions = document.querySelectorAll(
"#yes option:checked",
);
const existingNoOptions = document.querySelectorAll("#no option");
noSelect.replaceChildren(...selectedTransferOptions, ...existingNoOptions);
});
最終結果如下所示
規範
| 規範 |
|---|
| DOM # ref-for-dom-parentnode-replacechildren① |
瀏覽器相容性
載入中…