How to move an element into another element?

How to move an element into another element?

I would like to move one DIV element inside another. For example, I want to move this (including all children):

into this:

so that I have this:

Solutions/Answers:

Solution 1:

You may want to use the appendTo function (which adds to the end of the element):

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

Alternatively you could use the prependTo function (which adds to the beginning of the element):

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

Example:

$("#appendTo").click(function() {
  $("#moveMeIntoMain").appendTo($("#main"));
});
$("#prependTo").click(function() {
  $("#moveMeIntoMain").prependTo($("#main"));
});
#main {
  border: 2px solid blue;
  min-height: 100px;
}

.moveMeIntoMain {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">main</div>
<div id="moveMeIntoMain" class="moveMeIntoMain">move me to main</div>

<button id="appendTo">appendTo main</button>
<button id="prependTo">prependTo main</button>

Solution 2:

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.

Solution 3:

I just used:

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

Which I grabbed from here.

Solution 4:

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.

Solution 5:

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.

Solution 6:

You can use:

To Insert After,

jQuery("#source").insertAfter("#destination");

To Insert inside another element,

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