57

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?

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Cheeso
  • 189,189
  • 101
  • 473
  • 713

11 Answers11

83

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>
user10089632
  • 5,216
  • 1
  • 26
  • 34
graphicdivine
  • 10,937
  • 7
  • 33
  • 59
  • 14
    One major difference is the "return" value. The instance whose function you call is the instance that is returned – Casebash Oct 26 '11 at 04:06
  • 2
    glad you used the word 'opposite' so I could find this :-) – Simon_Weaver May 09 '15 at 03:39
  • @user10089632 - I saw your suggested edit, and approved it. But it really should stand alone as its own answer. It's much more clear than any of the other answers, including this one, and by providing it as an answer, you'll get reputation. Hopefully over time, your answer would get more upvotes than this one. – Scott Mermelstein Sep 27 '17 at 14:18
24

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.

Strongground
  • 25
  • 1
  • 8
Chris Clark
  • 4,544
  • 2
  • 22
  • 22
  • 2
    Incorrect, `after()` will return the context it is called on, in your example above `$("#foo").after("p")` would return `$("#foo")` allowing further chaining commands. – Timothy Walters Apr 07 '14 at 06:16
14

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>
Dexter
  • 18,213
  • 4
  • 44
  • 54
  • 3
    -1 for being incorrect. Both methods will move the element if there is only one target element, or create clones if there are more than one target element. – Timothy Walters Apr 07 '14 at 06:14
12

( after & before ):

$('selector').after('new_content');
$('selector').before('new_content');

while ( insertAfter & insertBefore ):

$('new_content').insertAfter('selector');
$('new_content').insertBefore('selector');
bjb568
  • 11,089
  • 11
  • 50
  • 71
Hazem_M
  • 549
  • 5
  • 11
6
$("p").insertAfter("#foo");

==

$("#foo").after("p")
Svetlozar Angelov
  • 21,214
  • 6
  • 62
  • 67
2

Check the documentation:

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

is the same as:

$("p").insertAfter("#foo");
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
1

after( content ) Returns: jQuery

Insert content after each of the matched elements.

insertAfter( selector ) Returns: jQuery

Insert all of the matched elements after another, specified, set of elements.

just somebody
  • 18,602
  • 6
  • 51
  • 60
1

One important things apart some syntax is that memory leak and performance. insertafter is more efficient than insert when you have tons of dom elements. So prefer insertafter instead of after.

sumit sharma
  • 698
  • 5
  • 16
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). - [From Review](/review/low-quality-posts/11100899) – dotnetom Feb 01 '16 at 18:37
  • 2
    @dotnetom This is most definitely an attempt to answer. This should not have been flagged, and should not be recommended for deletion in the LQPRQ. See: [You're doing it wrong: A plea for sanity in the Low Quality Posts queue](http://meta.stackoverflow.com/q/287563/4639281) and [Your answer is in another castle: when is an answer not an answer?](http://meta.stackexchange.com/q/225370/288751) –  Feb 02 '16 at 02:43
0

Here you can find a very very good tutorial of how to add content to a page using the jQuery methods prepend(), prependTo(), append(), appendTo(), before(), insertBefore(), after(), insertAfter(), wrap(), wrapAll() and wrapInner()

warmth
  • 467
  • 6
  • 10
0

After() and Insertafter() both appends an element, the major change will come for chaining

In after() you are appending the new element after your selector and then if you are using chain for the element then any function you used will fire on the selector not on the newly added element, and the opposite will performed in insertAfter() in which the chaining will performed on the newly added element for example,

After() and InsertAfter()

HTML

<div class="after">After Div</div>
------------------------------------------------------
<div class="insertafter">Insert after div</div>

SCRIPT

var p='<p>Lorem ipsum doner inut..</p>';
$('.after').after(p)//chaining, performed on .after div not on p
           .css('backgroundColor','pink');
           //you can chain more functions for .after here


$(p).insertAfter('.insertafter')//chaining, performed on p not on .insertafter div
    .css('backgroundColor','yellow');
    // here you can chain more functions for newly added element(p)

See above the selector and contents are changing in both functions. The same will apply on the list of following:

  1. before() vs insertBefore()
  2. append() vs appendTo()
  3. prepend() vs prependTo()
  4. and after() vs insertAfter(), obviously.

Live Demo

If you want to see both, performance wise then after() is faster than insertAfter() See after-vs-insertafter-performance.

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

It also seems that passing attributes of the inserted element doesn't work with ".insertAfter", but works with ".after"

works:

$('#element').after('<p>Test</p>', { 'class': 'element_class', 'id': 'element_id' });

doesn't work:

$('<p>Test</p>', { 'class': 'element_class', 'id': 'element_id' }).insertAfter('#element');

*edit: seems it doesn't work with ".after" neither, but only with ".appendTo"

bogdan
  • 1,269
  • 3
  • 12
  • 18