jQuery: What's the difference between after() and insertAfter()

jQuery has an .after() method, and also an .insertAfter() method.

What's the difference between them? I think I can use .after() to insert elements after a selected element (or elements). Is that right? What's .insertAfter() for?


They are mutual opposites.

'after' inserts the argument after the selector.

'insertAfter' inserts the selector after the argument.

Here is an example of the same thing done with:

insertafter():

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>
$( "<p>Test</p>" ).insertAfter( ".inner" );
Each inner <div> element gets this new content:
<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <p>Test</p>
  <div class="inner">Goodbye</div>
  <p>Test</p>
</div>

after():

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>
$( ".inner" ).after( "<p>Test</p>" );

<div class="container">
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <p>Test</p>
  <div class="inner">Goodbye</div>
  <p>Test</p>
</div>

They are inverses of each other. As explained in the jQuery documentation:

This:

$("p").insertAfter("#foo");

Is the same as this:

$("#foo").after("p");

And lastly, insertAfter returns all inserted elements, whereas .after() will return the context it is called on.


All of the answers so far are clear as mud ;-) (So I'll take a stab at it too!)

If you start off with this Html:

<p id="pOne">Para 1</p>
<p id="pTwo">Para 2 <span id="sMore">More</span></p>

After inserts some new content after the matching tags:

$("p")                       // Match all paragraph tags
    .after("<b>Hello</b>");  // Insert some new content after the matching tags

The end result is:

<p id="pOne">Para 1</p><b>Hello</b>
<p id="pTwo">Para 2 <span id="sMore">More</span></p><b>Hello</b>

On the other hand, InsertAfter moves one or more elements which already exist on the DOM after the selected elements (Really, this method could be called MoveAfter):

$("#sMore")                    // Find the element with id `sMore`
    .insertAfter("#pOne");     // Move it to paragraph one

Resulting in:

<p id="pOne">Para 1</p><span id="sMore">More</span>
<p id="pTwo">Para 2</p>