

新闻资讯
技术学院本文详解使用原生 javascript 批量移动(`appendchild`)或复制(`clonenode(true)`)多个 `
在前端开发中,经常需要将一组 HTML 元素(如多个
使用 appendChild() 可将元素从原父节点“移出”,并插入到目标容器末尾。由于 appendChild() 会自动从原位置解绑元素,无需手动 remove(),且多次调用会按顺序追加:
const destination = document.querySelector('ul.there');
document.querySelectorAll('ul.here > li').forEach(el => {
destination.appendChild(el); // 直接移动,原 ul.here 中对应 li 消失
});⚠️ 注意:appendChild() 是“移动”而非“复制”。执行后,ul.here 将变为空,所有 均出现在 ul.there 中。
若需保留原始结构,仅新增副本,则使用 cloneNode(true)(true 表示深克隆,包含子节点和事件监听器等):
const destination = document.querySelector('ul.there');
document.querySelectorAll('ul.here > li').forEach(el => {
destination.appendChild(el.cloneNode(true)); // 创建完整副本并追加
});⚠️ 注意:克隆后的元素是全新节点,不继承原元素绑定的事件监听器(除非手动重新绑定),且 id 属性若存在将重复,建议克隆后重置 id 避免冲突。
掌握 appendChild() 与 cloneNode(true) 的组合使用,即可高效、可靠地完成多元素批量迁移任务,无需依赖 jQuery 或大型框架。