We can use the jQuery insertBefore method to move an element before another element, or to insert a new element before another element.
$("#div2").insertBefore("#div1");
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 insertBefore() method to do this with the following Javascript code.
$(".p3").insertBefore(".p1");
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(".p1").insertBefore(".p3");
Using the jQuery insertBefore() Method to insert HTML before a DIV
We can also use the insertBefore() Method to insert new HTML before another element. 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 before class “p2”. We can use the insertBefore() method to do this.
$('This is paragraph 1
').insertBefore(".p2");
The result would be as follows:
This is paragraph 1
This is paragraph 2
This is paragraph 3
This is paragraph 4
Hopefully this article has been useful for you to understand how the jQuery insertBefore() method works.