We can use the jQuery appendTo method to move an element after all other children elements of their parent.
$("#div1").appendTo("#div2");
Let’s say I have the following HTML:
This is paragraph 1
This is paragraph 2
This is paragraph 3
If we want to move paragraph 1 after paragraph 3, then we can use the jQuery appendTo() method to do this with the following Javascript code.
$(".p1").appendTo("#div1");
The result would be as follows:
This is paragraph 2
This is paragraph 3
This is paragraph 1
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery(".p1").appendTo("#div1");
The appendTo method can be less useful than say the insertAfter() method as it only will bring the selected element to the end of the parent element’s children, while the insertAfter() method can be used to move the selected element after any other element on the page.
The append method is also very similar to the jQuery append() method, it’s main difference just being a syntax one. But both can accomplish the same thing.
Using the appendTo() Method to insert HTML into a DIV
We can also use the appendTo() Method to insert HTML into the end of a div. Take the following HTML:
This is paragraph 1
This is paragraph 2
This is paragraph 3
Say we wanted to add a new paragraph to #div1, right below class “p3”. We can use the appendTo() method to do this.
$('This is paragraph 4
').appendTo("#div1");
The result would be as follows:
This is paragraph 1
This is paragraph 2
This is paragraph 3
This is paragraph 4
Using the appendTo() Method to Move An Element After Another With a Click
We can use the jQuery appendTo() method to move an element after all other elements of their parent element.
Let’s say we have the following HTML code and we want to give the user the ability to move paragraph 2 to the bottom.
This is paragraph 1
This is paragraph 2
This is paragraph 3
This is paragraph 4
Move Paragraph 2
We can utilize both the jQuery click() method and jQuery appendTo() method to move paragraph 2 to the bottom.
Below is the Javascript code which will allow the user to be able to move paragraph 2 after all the other paragraphs of #div1.
$("#click-me").click(function(){
$(".p2").appendTo("#div1"); // results in paragraph 2 being moved after all other elements of #div1
});
The final code and output for this example of how to move an element after another using the jQuery appendTo() method and Javascript is below:
Code Output:
This is paragraph 1
This is paragraph 2
This is paragraph 3
This is paragraph 4
Full Code:
This is paragraph 1
This is paragraph 2
This is paragraph 3
This is paragraph 4
Move Paragraph 2
Hopefully this article has been useful for you to understand how the jQuery appendTo() method works.