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?
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?
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:
After inserts some new content after the matching tags:
The end result is:
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):
Resulting in:
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 theselector
not on the newly added element, and the opposite will performed ininsertAfter()
in which the chaining will performed on the newly added element for example,After() and InsertAfter()
HTML
SCRIPT
See above the
selector
andcontents
are changing in both functions. The same will apply on the list of following:Live Demo
If you want to see both, performance wise then
after()
is faster thaninsertAfter()
See after-vs-insertafter-performance.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():
after():
==
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.
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()