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 insertAfter() Method The insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.
. append() adds the parameter element inside the selector element's tag at the very end whereas the . after() adds the parameter element after the element's tag.
The jQuery after() method is used to insert content after the selected elements.
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:
<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>
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With