I would like to move one DIV element inside another. For example, I want to move this (including all children):
<div id="source">
...
</div>
into this:
<div id="destination">
...
</div>
so that I have this:
<div id="destination">
<div id="source">
...
</div>
</div>
You may also try:
But this will completely overwrite anything you have in
#destination
.Old question but got here because I need to move content from one container to another including all the event listeners.
jQuery doesn't have a way to do it but standard DOM function appendChild does.
Using appendChild removes the .source and places it into target including it's event listeners: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild
You may want to use the
appendTo
function (which adds to the end of the element):Alternatively you could use the
prependTo
function (which adds to the beginning of the element):Example:
If the
div
where you want to put your element has content inside, and you want the element to show after the main content:If the
div
where you want to put your element has content inside, and you want to show the element before the main content:If the
div
where you want to put your element is empty, or you want to replace it entirely:If you want to duplicate an element before any of the above:
What about a JavaScript solution?
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);
Check it out.
Ever tried plain JavaScript...
destination.appendChild(source);
?