如何将多个HTML元素复制或移动到另一个div元素中?
HTML元素的复制与移动实现方案
效果一:复制<li>至目标列表(保留原列表内容)
实现将.here下的所有<li>复制一份到.there列表,原列表内容保持不变。
原生JavaScript实现
const source = document.querySelector('.here'); const target = document.querySelector('.there'); // 深复制每个li并添加到目标列表 source.querySelectorAll('li').forEach(li => { target.appendChild(li.cloneNode(true)); });
jQuery实现
// 克隆li元素并追加到目标列表 $('.here li').clone().appendTo('.there');
效果二:移动<li>至目标列表(清空原列表)
实现将.here下的所有<li>转移到.there列表,原列表变为空。
原生JavaScript实现
const source = document.querySelector('.here'); const target = document.querySelector('.there'); // 循环移动所有子元素,appendChild会自动移除原父节点中的元素 while (source.firstChild) { target.appendChild(source.firstChild); }
jQuery实现
// 直接移动li元素到目标列表 $('.here li').appendTo('.there');
内容的提问来源于stack exchange,提问作者venndi
相关产品推荐
相关产品推荐

