jQuery

jQuery Move DIV into another DIV – 2 Very Easy Ways

Have you ever wanted to use jQuery to move a div along with all its content into another div? It is possible using jQuery.  This can be really helpful when you have elements on the page that are dynamically created. Read on to find out how you can move a div into another div.

How to Move DIV into another DIV using jQuery – Examples

Let’s say that you have two div’s with ID: “my_source_div” and “my_destination_div”. You would now like to move the “my_source_div” into “my_destination_div” so that the “my_source_div” becomes a part of the content of “my_destination_div” and appears as one among them. In this case, there are 2 possibilities. They are:

  1. Move “my_source_div” into “my_destination_div” so that “my_source_div” appears before the content of  “my_destination_div”.
  2. Move “my_source_div” into “my_destination_div” so that “my_source_div” appears after the content of  “my_destination_div”.

Let’s take a look at both the above possibilities by means of an example for each of them.

Example 1: By using .prependTo() method in jQuery

<style type="text/css">
#my_source_div {
	background-color: #D7FFD7;
	border: 1px solid #090;
	padding: 20px;
	margin-top: 10px;	
}

#my_destination_div {
	background-color: #E1F3FF;
	border: 1px solid #09F;
	padding: 20px;
	margin-top: 10px;
}
</style>

	<div id="my_source_div">

		Some content of source div.

	</div>

	<div id="my_destination_div">

		Some content of destination div.

	</div>        

<input type="submit" name="sbt_1" id="sbt_1" value="Move div using appendTo">

	$('#sbt_1').on("click", function(e){				

		$("#my_source_div").appendTo("#my_destination_div");

		e.preventDefault();

	});

When you run the above code and click the button, you will notice that all of the source div is merged into the destination div, along with all the contents and also appears before the content of the destination div.

Example 2: By using .appendTo() method in jQuery

	<div id="my_destination_div">

		Some content of destination div.

	</div>

<input type="submit" name="sbt_2" id="sbt_2" value="Move div using prependTo">

	$('#sbt_2').on("click", function(e){				

		$("#my_source_div").prependTo("#my_destination_div");

		e.preventDefault();

	});

When you run the above code and click the button, you will notice that all of the source div is merged into the destination div, along with all the contents and also appears after the content of the destination div.

Simple, isn’t it?

Do you know of any other ways to use  jQuery to move div into another div? Feel free to suggest by commenting below.

One Comment on jQuery Move DIV into another DIV – 2 Very Easy Ways

  1. 1

    Thanks for post! Using prependTo() if you want moving Div to top of element wrapped. Thanks man!

Share your thoughts, comment below now!

*

*