这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
ParentNode.replaceChildren()
方法将一个 Node
的后代替换为指定的后代集合。这些新的后代可以为 DOMString
或 Node
对象。
语法
// [Throws, Unscopable] ParentNode.replaceChildren(...nodesOrDOMStrings) // 返回 undefined
参数
异常
HierarchyRequestError
: 当违反了节点树的约束条件时抛出。
例子
清空一个节点
replaceChildren()
为清空一个节点的后代提供了非常方便的机制,您只需在父节点不指定任何实参调用该方法即可。
myNode.replaceChildren();
在父节点之间转移节点
replaceChildren()
允许您更轻松地在父节点之间转移节点,而无需依赖冗余的循环代码。例如,有一个简单的应用程序让您选择您派对上的食物。它的 HTML 可能如下:
<h2>派对食物列表</h2>
<main>
<div>
<label for="no">不,谢谢了!</label>
<select id="no" multiple size="10">
<option>苹果</option>
<option>橘子</option>
<option>葡萄</option>
<option>香蕉</option>
<option>奇异果</option>
<option>巧克力饼干</option>
<option>花生饼干</option>
<option>巧克力棒</option>
<option>火腿三明治</option>
<option>乳酪三明治</option>
<option>沙拉三明治</option>
<option>冰淇淋</option>
<option>果冻</option>
<option>胡萝卜和鹰嘴豆泥</option>
<option>玛格丽特披萨</option>
<option>腊肠比萨</option>
<option>素比萨</option>
</select>
</div>
<div class="buttons">
<button id="to-yes">转移到"是" --></button>
<button id="to-no"><-- 转移到 "否"</button>
</div>
<div>
<label for="yes">是的,请!</label>
<select id="yes" multiple size="10">
</select>
</div>
</main>
使用一些简单的 CSS 将两个选择列表排成一行,并将控制按钮放置在它们之间是很有意义的:
main {
display: flex;
}
div {
margin-right: 20px;
}
label, button {
display: block;
}
.buttons {
display: flex;
flex-flow: column;
justify-content: center;
}
select {
width: 200px;
}
我们要做的是,当按下 “是” 按钮时,将 “否” 列表中的所有选定选项都转移到 “是” 列表中,然后当按下“否”按钮时,将 “是” 列表中的所有选定选项都转移到 “否” 列表中。
为此,我们为每个按钮提供一个 click 事件处理句柄,该事件句柄将所选选项赋值到第一个常量中,将要转移到的列表中的现有的选项赋值到第二个常量中。然后,它会调用列表的 replaceChildren()
方法,使用延展运算符传入两个常量,进而将两个常量中包含的所有选项转移到目标列表。
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 ParentNode.replaceChildren() |
Living Standard | Initial definition. |
浏览器兼容性
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.