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
Coursera
Pros
  • Professional service
  • Flexible timetables
  • A variety of features to choose from
Main Features
  • Professional certificates of completion
  • University-level courses
  • Multiple Online degree programs
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.

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 30/01/2021
3176 People Used
Only 97 Left
Rating
5.0