To move an HTML element before another using jQuery the simplest way is to use the insertBefore() method.
$("#div-2").insertBefore("#div-1");
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(".p3").insertBefore(".p1");
If you’d instead like to move an element after another using jQuery, you can use the jQuery insertAfter() method.
Moving an Element Before Another Using jQuery With a Click
Many times when creating a web page and the user experience, we want to move a particular element based on an interaction with another element on the web page.
We can move an element before another element using jQuery very easily by combining the insertBefore() method with a click event.
Let’s say we have the following HTML code and we want to give the user the ability to move paragraph 3 before paragraph 2.
<div id="div1">
<p id="click-me">Click Me to Move Paragraph 3 before Paragraph 2</p>
<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>
We can utilize both the jQuery click() method and jQuery insertBefore() method to move paragraph 3 before paragraph 2.
Below is the Javascript code which will allow the user to be able to move paragraph 3 before paragraph 2:
$("#click-me").click(function(){
$(".p3").insertBefore(".p2"); // results in paragraph 3 being moved before paragraph 2
});
The final code and output for this example of how to move an element before another using jQuery and Javascript is below:
Code Output:
Click Me to Move Paragraph 3 before Paragraph 2
This is paragraph 1
This is paragraph 2
This is paragraph 3
Full Code:
<div class="html-code-output">
<div id="div1">
<p id="click-me">Click Me to Move Paragraph 3 before Paragraph 2</p>
<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>
</div>
<script>
$("#click-me").click(function(){
$(".p3").insertBefore(".p2"); // results in paragraph 3 being moved before paragraph 2
});
</script>
We can use the jQuery prependTo() method to move an element before all other elements in a parent element.
Hopefully this article has been useful for you to understand how to move an element before another using jQuery.
Leave a Reply