I would like to move one DIV element inside another. For example, I want to move this (including all children):
...
dirty size improvement of Bekim Bacaj answer
div { border: 1px solid ; margin: 5px }
<div id="source" onclick="destination.appendChild(this)">click me</div>
<div id="destination" >...</div>
You may also try:
$("#destination").html($("#source"))
But this will completely overwrite anything you have in #destination
.
I noticed huge memory leak & performance difference between insertAfter
& after
or insertBefore
& before
.. If you have tons of DOM elements, or you need to use after()
or before()
inside a MouseMove event, the browser memory will probably increase and next operations will run really slow.
The solution I've just experienced is to use inserBefore instead before()
and insertAfter instead after()
.
my solution:
MOVE:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
COPY:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
Note the usage of .detach(). When copying, be careful that you are not duplicating IDs.
If the div
where you want to put your element has content inside, and you want the element to show after the main content:
$("#destination").append($("#source"));
If the div
where you want to put your element has content inside, and you want to show the element before the main content:
$("#destination").prepend($("#source"));
If the div
where you want to put your element is empty, or you want to replace it entirely:
$("#element").html('<div id="source">...</div>');
If you want to duplicate an element before any of the above:
$("#destination").append($("#source").clone());
// etc.
Ever tried plain 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>