如何将一个元素移动到另一个元素中?

IT技术 javascript jquery html
2021-02-06 18:04:32

我想将一个 DIV 元素移到另一个内部。例如,我想移动这个(包括所有孩子):

<div id="source">
...
</div>

进入这个:

<div id="destination">
...
</div>

所以我有这个:

<div id="destination">
  <div id="source">
    ...
  </div>
</div>
6个回答

您可能想要使用该appendTo函数(它添加到元素的末尾):

$("#source").appendTo("#destination");

或者,您可以使用该prependTo函数(添加到元素的开头):

$("#source").prependTo("#destination");

例子:

这是一篇关于在 jQuery 中移除、替换和移动元素的优秀文章:elated.com/articles/jquery-removing-replacing-moving-elements
2021-03-18 18:04:32
请注意 appendTo 的 jQuery 文档指出元素已移动:it will be moved into the target (not cloned) and a new set consisting of the inserted element is returned- api.jquery.com/appendto
2021-03-24 18:04:32
appenTo 是创建副本还是实际将整个 div 移动到目的地?(因为如果它复制,它会在通过 id 调用 div 时创建错误)
2021-03-26 18:04:32
你没有移动它,只是追加。下面的答案做了一个适当的移动。
2021-03-29 18:04:32
警告这在 jQuery mobile 中可能无法正常工作,因为它可能会创建元素的另一个副本。
2021-04-03 18:04:32

我的解决方案:

移动:

jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')

复制:

jQuery("#NodesToMove").appendTo('#DestinationContainerNode')

注意 .detach() 的用法。复制时,请注意不要复制 ID。

最佳答案。接受的答案会创建一个副本,不会像问题要求的那样移动元素。
2021-03-10 18:04:32
抱歉,但 Andrew Hare 接受的答案是正确的 - 分离是不必要的。在上面的 Pixic 的 JSFiddle 中尝试一下 - 如果您删除 detach 调用,它的工作方式完全相同,即它执行移动,而不是复制。这是只有一个更改的分支:jsfiddle.net/D46y5 如 API 中所述:api.jquery.com/appendTo:“如果以这种方式选择的元素插入到 DOM 中其他地方的单个位置,它将被移动进入目标(未克隆)并返回一个由插入元素组成的新集合”
2021-03-28 18:04:32

怎么样一个JavaScript的解决方案吗?

// Declare a fragment:
var fragment = document.createDocumentFragment();

// Append desired element to the fragment:
fragment.appendChild(document.getElementById('source'));

// Append fragment to desired element:
document.getElementById('destination').appendChild(fragment);

看看这个。

为什么使用 createDocumentFragment 而不是简单的 document.getElementById('destination').appendChild(document.getElementById('source'))?
2021-04-06 18:04:32

我刚用过:

$('#source').prependTo('#destination');

我从这里抓到的

好吧,当您想保留元素并稍后重新插入它时,分离很有用,但在您的示例中,无论如何您都会立即重新插入它。
2021-03-13 18:04:32

曾经尝试过普通的 JavaScript...destination.appendChild(source);吗?

onclick = function(){ destination.appendChild(source); }
div{ margin: .1em; } 
#destination{ border: solid 1px red; }
#source {border: solid 1px gray; }
<!DOCTYPE html>
<html>

 <body>

  <div id="destination">
   ###
  </div>
  <div id="source">
   ***
  </div>

 </body>
</html>