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().
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid certificates of completion
Udemy
Pros
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion
Datacamp
Pros
  • Great user experience
  • Offers quality content
  • Very transparent with their pricing
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

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.