Advertisement
Advertisement


How to move an element into another element?


Question

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>
2014/09/17
1
1716
9/17/2014 3:45:22 AM

Accepted Answer

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>

2017/07/23
54
7/23/2017 1:44:19 PM


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.

2015/10/22

I just used:

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

Which I grabbed from here.

2015/07/24

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.

2020/04/26

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.
2016/06/22

You can use:

To Insert After,

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

To Insert inside another element,

jQuery("#source").appendTo("#destination");
2013/06/24

Source: https://stackoverflow.com/questions/1279957
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]