The ability to manipulate and rearrange the structure of a web page on the fly is a powerful feature that can greatly enhance user experience.
jQuery is a popular JavaScript library that enables users to move elements, such as a div, from one place to another within a web page.
Whether you’re looking to create dynamic and interactive user interfaces or simply rearrange your page layout based on certain conditions, the capability to move div elements with jQuery opens up a world of possibilities.
This article will give you a comprehensive guide on – how to move a div in another div with jQuery.
It will also include code snippets you can copy and test on your PC.
Before diving further, let’s look at two jQuery methods that will always come in handy when trying to manipulate and rearrange the structure of your web page by moving elements.
- The jQuery remove() method.
- The jQuery detach() method.
Understanding the jQuery remove() Method
The jQuery .remove() method removes elements from a web page directly from the HTML or using jQuery manipulation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").remove(); }); }); </script> </head> <body> <div id="div1"> <p>This is a paragraph in a div element.</p> </div> <button>Remove the div element</button> </body> </html> |
In this example, a button element is created that, when clicked, triggers the remove() method to remove the div element with an ID of “div1”.
The remove() method returns a set of elements that have been removed and are stored in a jQuery object.
However, it also eliminates all data and events connected to the removed elements created using jQuery.
So, if you had previously attached a jQuery click event to an element and then used remove() to remove that element, the click event would also be gone.
That could cause problems if you later want to add the element back to the page and still keep all its functions.
What is the solution? Using the jQuery detach() method.
Understanding the jQuery detach() Method
The jQuery.detach() method is an alternative to remove() and is often used when you need to move elements within a web page rather than simply removing them.
Unlike remove(), detach() only temporarily removes elements from the page rather than permanently deleting them.
This means that all data and events associated with the detached elements are preserved, allowing you to reattach these elements later with all their functionality intact.
This makes detach() a better choice than remove() when you need to move elements within a page.
1. Move Div in Another Div with jQuery append() Method
The .append() method in jQuery is used to insert content as the last child of the selected element(s). The content can be either an HTML string, a DOM element, or a jQuery object.
For example, the code below will add a new paragraph element with the text “New Content” as the last child of the element with the id “container”.
1 |
$("#container").append("<p>New Content</p>"); |
You can also use .append() to move elements from one place to another by passing a reference to the element you want to move. Have a look at the HTML code below.
1 2 3 4 5 6 7 8 9 |
<body bgcolor="skyblue"> <div id="container_1"> <p>I am Container One</p> </div> <div id="container_2"> <p>I am Container 2 in this Context</p> </div> </body> |
We will use the code below to move “container_2” and place it inside “container_1”.
1 2 3 4 5 |
$(document).ready(function () { var myDiv1Para = $(".container_2").detach(); $(".container_1").append($(myDiv1Para)) }); |
This code block uses the $(document).ready() function – a jQuery event that fires when the DOM is fully loaded and ready for manipulation.
This ensures that the code inside the function only runs when the entire page is ready and not before, which would cause errors.
The code above has two main parts:
- The first line uses the .detach() method on the element with the class container_2 to remove the selected elements from the DOM but keep their data and events intact so they can be re-inserted later.
- The second line uses the .append() method on the element with the class container_1, passing myDiv1Para as an argument. This line re-inserts the detached element (myDiv1Para) as the last child of the element with the class container_1.
The image below shows the new structure of the HTML code after running the jQuery script.
2. Move Div in Another Div with jQuery appendTo() Method
The .appendTo() method is similar to the append() method in that they both add elements to the end of the selected elements.
The only difference is their syntax.
The .append() method takes one or more elements as an argument and appends them to the end of each selected element.
1 2 |
var myDiv1Para = $(".container_2").detach(); $(".container_1").append($(myDiv1Para)) |
The .appendTo() method on the other hand takes the selected elements and appends them to the end of the target element specified as an argument.
Take a look at the jQuery code below.
1 2 3 4 |
$(document).ready(function () { var myDiv1Para = $(".container_2").detach(); $(myDiv1Para).appendTo($(".container_1")) }); |
The image below shows the new HTML structure after running the jQuery script.
The choice between using .append() or .appendTo() depends on what you want to emphasize as the target element, whether it is the new element being added or the existing element being targeted.
Both methods produce the same result, but their syntax is just written in a different order.
3. Move Div in Another Div with jQuery prepend() Method
The .prepend() method in jQuery inserts content at the beginning of the selected elements. It can add content either as an HTML string, or as a DOM element.
The content can be text, HTML, or other elements. For example:
1 |
$( "#myList" ).prepend( "<li>Prepended item</li>" ); |
This will insert an <li> element with text “Prepended item” at the beginning of the element with id “myList”.
Have a look at the HTML code below.
1 2 3 4 5 6 7 8 9 |
<body bgcolor="skyblue"> <div id="container_1"> <h2>I AM ELEMENT ONE</h2> </div> <div id="container_2"> <h2>I AM ELEMENT TWO. PLEASE MOVE ME!</h2> </div> </body> |
Here, we have two standalone divs with the IDs “container_1” and “container_2.” We will use the code below to detach the “container_2” div and insert it in “container_1.”
1 2 3 4 5 6 |
$(document).ready(function () { let removedElement = $("#container_2").detach(); $("#container_1").prepend($(removedElement)); }); |
The element with id “container_2” is first detached and stored in the removedElement variable.
Then, the .prepend() method is used to insert the removedElement (the detached element) at the beginning of the element with id “container_1”.
This results in the element with id “container_2” being moved to the beginning of the element with id “container_1”. See the image below.
4. Move Div in Another Div with jQuery prependTo() Method
The .prependTo() method in jQuery is similar to the .prepend() method, but with the elements and their target reversed.
Instead of adding content to the beginning of the selected elements, the prependTo() method moves the selected elements to the beginning of the target elements.
For example:
1 |
$("<li>Prepended item</li>").prependTo("#myList"); |
This will insert an <li> element with text “Prepended item”</li> at the beginning of the element with id “myList.”
The main difference between .prepend() and .prependTo() is the order of their arguments:
- .prepend(content, target)
- .prependTo(target, content)
Both methods achieve the same result, but with a different ordering of the target and content elements.
In our case, we would use the code below to detach the “container_2” div and insert it in “container_1.”
1 2 3 4 5 6 |
$(document).ready(function () { let removedElement = $("#container_2").detach(); $(removedElement).prependTo($("#container_1")) }); |
You will notice that you get the same results as using the prepend() method. See the image below.
The choice between the two methods is mostly a matter of personal preference.
To summarize, in the next section, you will find a summary about the 4 best ways to move a div into another div with jQuery based on what we have learned in this article:
How to Move a Div in Another Div with jQuery
The ability to move a div element into another div within a web page can be achieved using jQuery’s functions such as append(), prepend(), appendTo(), and prependTo(). These functions allow you to specify where the div should be moved to and can greatly enhance the dynamic behavior of your web pages.
Frequently Asked Questions About How To Move Div in Another Div with jQuery
How can I insert a div before or after another div using jQuery?
You can use the .InsertBefore() or .InsertAfter() method to insert a div before or after another div. For example:
$(“<div>”).insertBefore(“#targetDiv”);
$(“<div>”).insertAfter(“#targetDiv”);
How can I replace one div with another div using jQuery?
You can use the .replaceWith() method to replace one div with another div. For example:
$(“#sourceDiv”).replaceWith(“#targetDiv”);
Note: The .replaceWith() method completely replaces the selected element with the specified element, so in this case, the #sourceDiv element would be removed.