Black friday

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

jQuery .after(): Insert Content After Specified Elements

Reading time 2 min
Published Jan 17, 2018
Updated Oct 2, 2019

jQuery after: Main Tips

  • jQuery .after() method inserts content after the selected element.
  • While it works very similarly to the .insertAfter() method, it uses different syntax, which can be important when you're chaining statements.
  • To insert content before the element, use .before().
Theory is great, but we recommend digging deeper!

Using .after() in jQuery

The .after() method makes jQuery append (add content after) elements. In the example below, you can see an additional text paragraph appears below the heading as you click the button:

Example
$("button").click(() => {
    $("h2").after("<p>Surprise text!</p>");
});

Syntax for .after()

The syntax for jQuery .after() is as follows:

$("selector").after(content);

The selector defines the element after which the content will be inserted. The content can refer to jQuery object, DOM element, HTML string, or a text node. It can also be an array of elements or nodes.

If you need to specify more than one piece of content to go after an element, separate them by commas:

$("selector").after(content, content, content, [...]);

Note: since version 1.4, you can also define the content for .after() in jQuery by naming a function that will return the content to add.

Syntax is also where .after() differs from the .insertAfter() method. While they both have the same purpose, their syntax is exactly opposite:

Method Syntax
.after() $("selector").after(content);
.insertAfter() $("content").after(selector);

This is especially important when you're using chained statements. When chaining, you apply multiple methods using a single statement, so it is very handy to be able to choose the selector for it more freely.