We can use the jQuery insertAfter method to move an element after another element, or to insert a new element after another element.

$("#div1").insertAfter("#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 insertAfter() method to do this with the following Javascript code.

$(".p1").insertAfter(".p3");

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").insertAfter(".p3");

Using the jQuery insertAfter() Method to insert HTML after a DIV

We can also use the insertAfter() Method to insert new HTML after another element. 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 insertAfter() method to do this.

$('

This is paragraph 4

').insertAfter(".p3");

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 insertAfter() method works.

Categorized in:

jQuery,

Last Update: March 20, 2024