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:
<div id="div1">
<p class="p1">This is paragraph 1</p>
<p class="p2">This is paragraph 2</p>
<p class="p3">This is paragraph 3</p>
</div>
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:
<div id="div1">
<p class="p2">This is paragraph 2</p>
<p class="p3">This is paragraph 3</p>
<p class="p4">This is paragraph 4</p>
</div>
Say we wanted to add a new paragraph to #div1, right before class “p2”. We can use the insertBefore() method to do this.
$('<p class="p1">This is paragraph 1</p>').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.
Leave a Reply