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

JavascriptJqueryInsertafterJquery After

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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():

>

>

Greetings

>
Hello
>
Goodbye
>
> $( "

Test

" ).insertAfter( ".inner" ); > Each inner
element gets this new content: >
>

Greetings

>
Hello
>

Test

>
Goodbye
>

Test

>

after():

>

>

Greetings

>
Hello
>
Goodbye
>
> $( ".inner" ).after( "

Test

" ); >
>
>

Greetings

>
Hello
>

Test

>
Goodbye
>

Test

>

Solution 2 - Javascript

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.

Solution 3 - Javascript

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>

Solution 4 - Javascript

( after & before ):

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

while ( insertAfter & insertBefore ):

$('new_content').insertAfter('selector');
$('new_content').insertBefore('selector');

Solution 5 - Javascript

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

==

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

Solution 6 - Javascript

Check the documentation:

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

is the same as:

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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.

Solution 9 - Javascript

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"

Solution 10 - Javascript

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()

Solution 11 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCheesoView Question on Stackoverflow
Solution 1 - JavascriptgraphicdivineView Answer on Stackoverflow
Solution 2 - JavascriptChris ClarkView Answer on Stackoverflow
Solution 3 - JavascriptDexterView Answer on Stackoverflow
Solution 4 - JavascriptHazem_MView Answer on Stackoverflow
Solution 5 - JavascriptSvetlozar AngelovView Answer on Stackoverflow
Solution 6 - JavascriptkgiannakakisView Answer on Stackoverflow
Solution 7 - Javascriptjust somebodyView Answer on Stackoverflow
Solution 8 - Javascriptsumit sharmaView Answer on Stackoverflow
Solution 9 - JavascriptbogdanView Answer on Stackoverflow
Solution 10 - JavascriptwarmthView Answer on Stackoverflow
Solution 11 - JavascriptRohan KumarView Answer on Stackoverflow