In this simple tutorial you will learn how to move div in another div with jQuery. This trick is useful when you have limited access to html source or when you need a quick way to move an element in another element without changing the html.
As an introduction in this move div in another div tutorial, I will start with an example with 1 main div A, which includes another 2 divs B and C. These 2 divs includes, each, one more div, D and E. Check the example below.
<div class="divA"> <div class="divB"> <div class="divD"></div> </div> <div class="divC"> <div class="divE"></div> </div> </div>
First, make sure you are loading the latest jQuery Library in your html document. You can download jQuery files from here.
Assume that you want to move div C inside div B. The problem is that inside div B there is another div. To move div in another div with jQuery you need first to think where your div must be positioned (above or below the content). I will show you both ways.
Now that you have everything loaded, is time to move div in another div with jQuery, under the content where you are moving the div. Keep in mind when targeting an object using appendTo(); function, container will be moved exactly inside the object selected, at the bottom. Check the example below:
<script> $('.divC').appendTo('.divB'); </script>
Remember to always add the script right above the ending of the </body> tag. The script above will move div C container, inside div B, exactly at the end (under div D).
This function is exactly the opposite of appendTo. Using prependTo(); will move div in another div above the content.
<script> $('.divC').prependTo('.divB'); </script>
Using my example above, div C should be moved inside div B, above div D. Check the sample image below:
This function is a bit different than appendTo. What insertAfter(); does, is to place your selected object under the targeted object.
<script> $('.divE').insertAfter('.divB'); </script>
For example, if we select div E and target div B, our container div E will be moved exactly after div B. Check the sample image:
Function insertBefore(); does almost the same thing as insertAfter. It will only move the selected div above the targeted div.
<script> $('.divE').insertBefore('.divB'); </script>
Using our example, if you select div E and target div B, container div E will be moved exactly above div B. Check the example below:
Hope this tutorial was helpful and clear for everyone. You can also try the Full HD video from the beginning of the article and see a live example on how to move div in another div with jQuery.
If this tutorial was useful, you can help me maintain this website with more tutorials by buying me a coffe (or at least the sugar).