By Mark Richman


2009-08-14 20:14:45 8 Comments

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>

14 comments

@spetsnaz 2014-08-23 21:16:01

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().

@Mark Richman 2014-08-23 21:17:13

This sounds like a JavaScript engine implementation-dependent issue. Which browser version and JS engine do you see this with?

@spetsnaz 2014-08-23 21:29:01

I'm on Chrome version 36.0.1985.125 and using jQuery v1.11.1. I bind a function on mousemove event, which moves a simple DIV to down or up the element that mouse is over. Therefore, this event & function runs while you drag your cursor. The memory leak occurs with after() and before(), if you move your cursor for 30sec+, and it disappears if I just use insertAfter & insertBefore instead.

@Mark Richman 2014-08-23 21:33:28

I'd open a bug with Google on that one.

@Alireza 2019-01-19 00:55:56

You can use pure JavaScript, using appendChild() method...

The appendChild() method appends a node as the last child of a node.

Tip: If you want to create a new paragraph, with text, remember to create the text as a Text node which you append to the paragraph, then append the paragraph to the document.

You can also use this method to move an element from one element to another.

Tip: Use the insertBefore() method to insert a new child node before a specified, existing, child node.

So you can do that to do the job, this is what I created for you, using appendChild(), run and see how it works for your case:

function appendIt() {
  var source = document.getElementById("source");
  document.getElementById("destination").appendChild(source);
}
#source {
  color: white;
  background: green;
  padding: 4px 8px;
}

#destination {
  color: white;
  background: red;
  padding: 4px 8px;
}

button {
  margin-top: 20px;
}
<div id="source">
  <p>Source</p>
</div>

<div id="destination">
  <p>Destination</p>
</div>

<button onclick="appendIt()">Move Element</button>

@RayLuo 2018-09-04 07:18:14

For the sake of completeness, there is another approach wrap() or wrapAll() mentioned in this article. So the OP's question could possibly be solved by this (that is, assuming the <div id="destination" /> does not yet exist, the following approach will create such a wrapper from scratch - the OP was not clear about whether the wrapper already exists or not):

$("#source").wrap('<div id="destination" />')
// or
$(".source").wrapAll('<div id="destination" />')

It sounds promising. However, when I was trying to do $("[id^=row]").wrapAll("<fieldset></fieldset>") on multiple nested structure like this:

<div id="row1">
    <label>Name</label>
    <input ...>
</div>

It correctly wraps those <div>...</div> and <input>...</input> BUT SOMEHOW LEAVES OUT the <label>...</label>. So I ended up use the explicit $("row1").append("#a_predefined_fieldset") instead. So, YMMV.

@Andrew Hare 2009-08-14 20:16:45

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>

@Jordan Reiter 2012-06-19 14:07:05

A warning that this may not work correctly in jQuery mobile, as it may create another copy of the element instead.

@user1031721 2012-07-12 22:04:00

does the appenTo create a copy or actually moves the whole div to the destination? (because if it copies, it would create erros when calling the div by the id)

@Jason 2012-07-26 22:57:53

Worked for me in jQuery Mobile. Thanks!

@moondog 2012-08-27 21:19:12

Should '#destination' be '$("#destination")': $("#source").appendTo($("#destination"));

@Samuel 2012-08-28 14:50:20

@user606696 From the docs: "target: A selector, element, HTML string, or jQuery object".

@xhh 2012-12-03 07:55:34

Here is an excellent article on Removing, Replacing and Moving Elements in jQuery: elated.com/articles/jquery-removing-replacing-moving-element‌​s

@Josh 2013-01-24 04:30:06

It works correctly as written. The argument for appendTo() is a selector as a string, NOT a jQuery object.

@John K 2014-01-13 01:10:37

Note the jQuery documentation for appendTo states the element is moved: it will be moved into the target (not cloned) and a new set consisting of the inserted element is returned - api.jquery.com/appendto

@Aaron 2014-05-28 03:42:20

You are not moving it, just appending. Below answer does a proper MOVE.

@Zafar 2014-08-28 23:32:38

this copies. doesn't move. @Alejandro Illecas' answer moves.

@JackArbiter 2014-10-17 14:45:39

This moves, doesn't copy. See actual documentation listed above by John K, not random people posting incorrect comments even after he posted it.

@Vincent Pazeller 2015-02-16 09:57:55

The documentation also says: "If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.". So in the general case, this solution CAN create copies!

@kevinmicke 2016-11-12 21:00:45

If you're seeing copies created, it's probably related to the comment from @VincentPazeller above about there being more than one target. A fix for this that worked in my situation (moving <li> into empty <ol>) was simply to add .last() when I called .children(). Code before fix that created copies: $(this).appendTo($(this).prev().children("ol"));. Code after fix that moved element as intended: $(this).appendTo($(this).prev().children("ol").last());

@Sonhja 2017-09-18 07:16:32

If you are trying to move all content AFTER a specific div, you could also use the insertAfter function. This will move a Div after a specified id: api.jquery.com/insertafter.

@Jinghui Niu 2019-12-18 09:19:37

jQuery is not a wise move.

@Bekim Bacaj 2016-05-02 13:53:20

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>

@Bekim Bacaj 2017-07-23 13:56:59

* someone prefixed the global event onclick of the demo snippet with the keyword var in his/her attempt to enhance the post - but that's wrong!

@nkkollaw 2017-09-07 22:17:59

It's amazing how people still think jQuery equals JavaScript. No need for jQuery anymore in 2017, really.

@eballeste 2019-12-12 18:17:17

no need for jquery in 2017 but sometimes it helps to use something lighter and similar for tasks you find yourself doing over and over again in every single project. i use cash-dom as an easy way to listen for document.ready, window.load events in a cross-browser friendly way. easy-peasy.

@itsme 2012-11-25 19:52:53

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.

@Michael Scheper 2014-06-26 02:22:02

I'm finding all the boldface a bit hard to read, but this is the most informative answer, so it gets my upvote.

@Ali Bassam 2015-11-15 20:04:53

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.

@Gunar Gessner 2016-02-16 01:45:46

Why using createDocumentFragment instead of simply document.getElementById('destination').appendChild(document.‌​getElementById('sour‌​ce'))?

@Ali Bassam 2016-02-17 21:12:15

@GunarC.Gessner assuming you need to modify the source object before adding it to the destination object, then the best approach is to use the fragment which is an imaginary object and is not part of the DOM tree, you get better performance when modifying the source object when it has been transitioned from it's original place (now it's inside the fragment) rather than modifying it in it's initial place before appending it.

@Alexander Fradiani 2016-06-10 03:38:51

I want to add for the relevance of offering a JavaScript pure solution. It shouldn't be assumed jQuery is always being used

@jimasun 2016-11-15 09:19:54

Question: In appending the child node, are we losing the attached events?

@jimasun 2016-11-15 09:34:39

The answer to my own question is yes, it does keep the attached events.

@Subodh Ghulaxe 2015-11-02 08:49:15

You can use following code to move source to destination

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

try working codepen

function move() {
 jQuery("#source")
   .detach()
   .appendTo('#destination');
}
#source{
  background-color:red;
  color: #ffffff;
  display:inline-block;
  padding:35px;
}
#destination{
  background-color:blue;
  color: #ffffff;
  display:inline-block;
  padding:50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="source">
I am source
</div>

<div id="destination">
I am destination
</div>

<button onclick="move();">Move</button>

@Alejandro Illecas 2013-11-06 01:50:18

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.

@paulscode 2013-12-17 19:02:01

Best answer. Accepted answer creates a copy, doesn't move the element like the question asks for.

@John - Not A Number 2014-02-04 04:34:26

Sorry, but Andrew Hare's accepted answer is correct - the detach is unnecessary. Try it in Pixic's JSFiddle above - if you remove the detach calls it works exactly the same, i.e. it does a move, NOT a copy. Here's the fork with just that one change: jsfiddle.net/D46y5 As documented in the API: api.jquery.com/appendTo : "If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned) and a new set consisting of the inserted element is returned"

@LeonardChallis 2014-09-23 14:30:19

@John-NotANumber is right - detach() is not needed here. The accepted answer IS the best, you just need to actually read the documentation properly.

@Vincent Pazeller 2015-02-16 10:01:03

The appendTo documentation also says: "If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.". So in the general case, this solution CAN also create copies!

@Victor Augusto 2016-10-02 19:43:05

great! Or you can use this to be more specific about where to move $('#nodeToMove').insertAfter('#insertAfterThisElement');

@Meloman 2017-04-10 13:10:47

I added .hide() and .show() because vvertical scrollbar appears in my case and I wouldn't : jQuery("#NodesToMove").hide().detach().appendTo('#Destinatio‌​nContainerNode').sho‌​w();

@Semmel 2019-03-13 16:34:33

This is my preferred answer as I'm moving one element to multiple locations - but the accepted answer better matches the OPs question (= move A to B).

@kjc26ster 2012-07-24 18:51:06

I just used:

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

Which I grabbed from here.

@Tim Büthe 2012-09-27 15:56:49

Well, detach is useful when you want to hold on to the element and reinsert it later on, but in your example you reinsert it instantly anyway.

@kjc26ster 2012-11-03 21:53:49

I'm afraid I'm not quite groking what you're getting at, could you provide sample code?

@Tim Büthe 2012-11-04 09:24:37

I mean, prependTo, detaches the element from its original position an inserts it at the new one. The detach function on the other hand just detaches the selected element and you can save it in a variable to insert it into the DOM at a later point in time. The thing is, your detach call is unnecessary. Remove it and you will achieve the same effect.

@hlscalon 2019-02-13 12:52:19

Incredible that the edits changed this answer completely to the point that another answer was added one year later (identical to the original) and got 800+ upvotes...

@Tamas 2012-12-05 12:40:21

You may also try:

$("#destination").html($("#source"))

But this will completely overwrite anything you have in #destination.

@Igor Pomaranskiy 2018-03-08 15:51:57

And break event listeners on the moved element.

@Dan 2015-02-17 22:03:13

If you want a quick demo and more details about how you move elements, try this link:

http://html-tuts.com/move-div-in-another-div-with-jquery


Here is a short example:

To move ABOVE an element:

$('.whatToMove').insertBefore('.whereToMove');

To move AFTER an element:

$('.whatToMove').insertAfter('.whereToMove');

To move inside an element, ABOVE ALL elements inside that container:

$('.whatToMove').prependTo('.whereToMove');

To move inside an element, AFTER ALL elements inside that container:

$('.whatToMove').appendTo('.whereToMove');

@HMR 2014-12-24 04:06:40

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.

//assuming only one .source and one .target
$('.source').on('click',function(){console.log('I am clicked');});
$('.target')[0].appendChild($('.source')[0]);

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

@Subrahmanyam 2013-06-24 10:43:04

You can use:

To Insert After,

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

To Insert inside another element,

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

Related Questions

Sponsored Content

93 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6260224 View
  • 7817 Score
  • 93 Answer
  • Tags:   javascript arrays

37 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

39 Answered Questions

[SOLVED] How do I loop through or enumerate a JavaScript object?

56 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

65 Answered Questions

[SOLVED] How do I check whether a checkbox is checked in jQuery?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

4 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

31 Answered Questions

[SOLVED] Make a div fill the height of the remaining screen space

  • 2008-09-18 05:06:17
  • Vincent McNabb
  • 937487 View
  • 1793 Score
  • 31 Answer
  • Tags:   html css html-table

Sponsored Content