为什么不能将克隆元素附加到另一个父元素上?

Why can't I append a cloned element to another parent?

本文关键字:元素 另一个 不能 为什么      更新时间:2023-09-26

我有两个div:

<div id='div1'>
  <span>text</span>
</div>
<div id='div2'>
</div>

我正在尝试将span从div1移动到div2:

  var div1 = document.querySelector('#div1');
  var div2 = document.querySelector('#div2');
  //cloning span
  var span = div1.firstElementChild.cloneNode();
  //removing span from the first div
  div1.removeChild(div1.firstElementChild);
  //trying to append new span to the second div but nothing happens
  div2.appendChild(span);

span元素被移除,但没有插入到第二个div中。

我错过了什么吗?

你需要一个深拷贝。cloneNode接受一个可选参数

 var span = div1.firstElementChild.cloneNode(true);

(here is a fiddle)

deep应该是true默认根据新的规范,在chrome和safari默认为false。