We can use the jQuery prependTo() method to move an element before all other children elements of their parent.
$("#div1").prependTo("#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 3 before paragraph 1, then we can use the jQuery prependTo() method to do this with the following Javascript code.
$(".p3").prependTo("#div1");
The result would be as follows:
This is paragraph 3
This is paragraph 1
This is paragraph 2
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery(".p3").prependTo("#div1");
The prependTo method can be less useful than say the insertBefore() method as it only will bring the selected element to the beginning of the parent element’s children, while the insertBefore() method can be used to move the selected element before any other element in the page.
Using the prependTo() Method to insert HTML into a DIV
We can also use the prependTo() Method to insert HTML into the start of a div. Take the following HTML:
This is paragraph 2
This is paragraph 3
This is paragraph 4
Say we wanted to add a new paragraph to #div1, right above class “p2”. We can use the prependTo() Method to do this.
$('This is paragraph 1
').prependTo("#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 prependTo() Method to Move An Element Before Another With a Click
We can use the jQuery prependTo() method to move an element before 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 3 to the top.
Click Me to Move Paragraph 3 before all the other elements
This is paragraph 1
This is paragraph 2
This is paragraph 3
This is paragraph 4
We can utilize both the jQuery click() method and jQuery prependTo() method to move paragraph 3 to the top.
Below is the Javascript code which will allow the user to be able to move paragraph 3 before all the other paragraphs in #div1.
$("#click-me").click(function(){
$(".p3").prependTo("#div1"); // results in paragraph 3 being moved before all other elements in #div1
});
The final code and output for this example of how to move an element before another using the jQuery prependTo() method and Javascript is below:
Code Output:
Click Me to Move Paragraph 3 before all the other elements below.
This is paragraph 1
This is paragraph 2
This is paragraph 3
This is paragraph 4
Full Code:
Click Me to Move Paragraph 3 before all the other elements below.
This is paragraph 1
This is paragraph 2
This is paragraph 3
This is paragraph 4
<script>
$("#click-me").click(function(){
$(".p3-1").prependTo("#div1-1"); // results in paragraph 3 being moved before all other elements in #div1
});
</script>
Hopefully this article has been useful for you to understand how to move an element before another using jQuery.