jQuery Move Div Contents To Another Div Examples
At times, it might be desirable to move contents of a div into another div, while retaining the divs themselves, as is. And in some other instances, you might want to delete the source div, once it’s contents are copied to the destination div. In this article, I am going to share a very easy way to move div contents to another div using jQuery. The actual code is just 1 line, so it’s super easy & simple to follow along. Read on to find out more.
Examples of using jQuery to Move Div Contents To Another Div
Let’s say that you have two div’s with ID: “my_source_div” and “my_destination_div”.
<div id="my_source_div"> Some content of source div. </div> <div id="my_destination_div"> </div>
Desired output:
<div id="my_destination_div"> Some content of source div. </div>
You would like to move the contents of the source div into the destination div. This can be easily done by using the code below:
Example: Move the Contents of a Div To Another Div using html() and Retain source div
$('#my_destination_div').html( $('#my_source_div').html() );Using the above code will simply copy the contents of the source div to the destination div and will leave the source div intact. If you would like to remove the source div after the contents are copied, then use the example below.
Example: Move the Contents of a Div To Another Div using html() and Remove source div
$('#my_destination_div').html( $('#my_source_div').html() );
$('#my_source_div').remove();The above example will remove the source div immediately after it’s contents are copied to the destination div.
Simple, isn’t it?
Do you know of any other ways to use jQuery to move div contents to another div? Feel free to suggest by commenting below.