We can use the jQuery after method to insert a new HTML element after another element.

$("#div1").after("
");

Let’s take a look at a quick example.


Let’s say we have the following HTML:

This is paragraph 1

This is paragraph 2

If we want to insert a new paragraph after paragraph with class “p2”, then we can use the jQuery after() method to do this with the following jQuery code.

$(".p2").after("

This is paragraph 3

");

The result would be as follows:

This is paragraph 1
This is paragraph 2
This is paragraph 3

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery(".p2").after("

This is paragraph 3

");

If you want to insert HTML before another element, we can do this with the jQuery before() method.

Using the jQuery after() Method to insert HTML after a Div on a Click

In this example, we will have a div that will be a box. We will then let the user insert a new box we create using the after() method as many times as they want.

Here is the HTML code:



Insert new box

The new code to create a box will just be a new div with the class “box”.

We will change the new box background color using the css() method and add it as a style attribute.

Also note that our original box will have a black border on it so we can keep track of it as we add boxes.

Here is the jQuery and JavaScript code:

$("#click-me").click(function(){
  //Create a random color
  var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
  //Create a new div with class box, and add the new color to it as a bg  
  $('#first-box').after("
"); });

The final code and output for this example of using the jQuery after() method to create a bunch of new box divs is below:

Code Output:

Insert new box

Full Code:



Insert new box

Hopefully this article has been useful for you to understand how to use the jQuery after method.

Categorized in:

jQuery,

Last Update: February 26, 2024