2 examples to insert HTML content by jQuery after method


2 examples to insert HTML content by jQuery after method

2 examples to insert HTML content by jQuery after method

The after method of jQuery

The jQuery after method allows adding the content after the specified element.

For example, you have a div or paragraph on your webpage and want to add some text content after the div or paragraph, you can use the after method of jQuery to do that.

An example of after method

You can also use the append method of jQuery to accomplish that, however, there is a difference explained at the bottom part of this tutorial with an example.

Syntax of using jQuery after

The simple syntax of using the after method is:

$(“element”).after(“Content to be added <b> can be in bold</b> with linebreaks <br> etc.”);

Example of using ‘after’ in jQuery with div element

The example below shows how to use the after method with div element to add some text. The added text will have some formatting like bold and line break as well. You can add links or other HTML tags as well.

jQuery after method

Experience this example online



Difference between ‘after’ and append methods of jQuery

The jQuery after method adds content “after” the boundary of the specified element. Whereas the append method adds the content within the boundary of the given element. The example below makes it clearer.

We have two buttons and two div elements.

As you click on the left button “Run after method”, it will add text by using “after jQuery method”.

As you click on the right button “Run append method”, it will add content by using append method of jQuery.

To make it clearer, both div elements are given borders.

jQuery after append

Experience this example online



As you can see, the content added by using the after method added content after the border of div element while the jQuery append method added within the border of the div element.

Related reading: append |  jQuery before method | jQuery click



jQuery Guide