簡體   English   中英

為什么不能將克隆的元素附加到另一個父元素?

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

我有兩個div:

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

<div id='div2'>
</div>

我正在嘗試將范圍從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);

(這是一個小提琴)

根據新規范,默認情況下, deep默認為true ,但在chrome和safari中,默認為false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM