.append(), prepend(), .after() and .before()

JavascriptJqueryAppendPrependJquery After

Javascript Problem Overview


I am pretty proficient with coding, but now and then I come across code that seems to do basically the same thing. My main question here is, why would you use .append() rather then .after() or vice verses?

I have been looking and cannot seem to find a clear definition of the differences between the two and when to use them and when not to.

What are the benefits of one over the other and also why would i use one rather then the other?? Can someone please explain this to me?

var txt = $('#' + id + ' span:first').html();
$('#' + id + ' a.append').live('click', function (e) {
    e.preventDefault();
    $('#' + id + ' .innerDiv').append(txt);
});
$('#' + id + ' a.prepend').live('click', function (e) {
    e.preventDefault();
    $('#' + id + ' .innerDiv').prepend(txt);
});
$('#' + id + ' a.after').live('click', function (e) {
    e.preventDefault();
    $('#' + id + ' .innerDiv').after(txt);
});
$('#' + id + ' a.before').live('click', function (e) {
    e.preventDefault();
    $('#' + id + ' .innerDiv').before(txt);
});

Javascript Solutions


Solution 1 - Javascript

See:


.append() puts data inside an element at last index and
.prepend() puts the prepending elem at first index


suppose:

<div class='a'> //<---you want div c to append in this
  <div class='b'>b</div>
</div>

when .append() executes it will look like this:

$('.a').append($('.c'));

after execution:

<div class='a'> //<---you want div c to append in this
  <div class='b'>b</div>
  <div class='c'>c</div>
</div>

Fiddle with .append() in execution.

when .prepend() executes it will look like this:

$('.a').prepend($('.c'));

after execution:

<div class='a'> //<---you want div c to append in this
  <div class='c'>c</div>
  <div class='b'>b</div>
</div>

Fiddle with .prepend() in execution.

.after() puts the element after the element
.before() puts the element before the element


using after:

$('.a').after($('.c'));

after execution:

<div class='a'>
  <div class='b'>b</div>
</div>
<div class='c'>c</div> //<----this will be placed here

Fiddle with .after() in execution.

using before:

$('.a').before($('.c'));

after execution:

<div class='c'>c</div> //<----this will be placed here
<div class='a'>
  <div class='b'>b</div>
</div>

Fiddle with .before() in execution.

Solution 2 - Javascript

This image displayed below gives a clear understanding and shows the exact difference between .append(), .prepend(), .after() and .before()

jQuery infographic

You can see from the image that .append() and .prepend() adds the new elements as child elements (brown colored) to the target.

And .after() and .before() adds the new elements as sibling elements (black colored) to the target.

Here is a DEMO for better understanding.


EDIT: the flipped versions of those functions:

jQuery insertion infographic, plus flipped versions of the functions

Using this code:

var $target = $('.target');

$target.append('<div class="child">1. append</div>');
$target.prepend('<div class="child">2. prepend</div>');
$target.before('<div class="sibling">3. before</div>');
$target.after('<div class="sibling">4. after</div>');

$('<div class="child flipped">or appendTo</div>').appendTo($target);
$('<div class="child flipped">or prependTo</div>').prependTo($target);
$('<div class="sibling flipped">or insertBefore</div>').insertBefore($target);
$('<div class="sibling flipped">or insertAfter</div>').insertAfter($target);

on this target:

<div class="target">
    This is the target div to which new elements are associated using jQuery
</div>


So although these functions flip the parameter order, each creates the same element nesting:

var $div = $('<div>').append($('<img>'));
var $img = $('<img>').appendTo($('<div>'))

...but they return a different element. This matters for method chaining.

Solution 3 - Javascript

append() & prepend() are for inserting content inside an element (making the content its child) while after() & before() insert content outside an element (making the content its sibling).

Solution 4 - Javascript

The best way is going to documentation.

.append() vs .after()

  • .append(): Insert content, specified by the parameter, to the end of each element in the set of matched elements.
  • .after(): Insert content, specified by the parameter, after each element in the set of matched elements.

.prepend() vs .before()

  • prepend(): Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
  • .before(): Insert content, specified by the parameter, before each element in the set of matched elements.

So, append and prepend refers to child of the object whereas after and before refers to sibling of the the object.

Solution 5 - Javascript

There is a basic difference between .append() and .after() and .prepend() and .before().

.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 vice-versa is for .prepend() and .before().

Fiddle

Solution 6 - Javascript

There is no extra advantage for each of them. It totally depends on your scenario. Code below shows their difference.

    Before inserts your html here
<div id="mainTabsDiv">
    Prepend inserts your html here
    <div id="homeTabDiv">
        <span>
            Home
        </span>
    </div>
    <div id="aboutUsTabDiv">
        <span>
            About Us
        </span>
    </div>
    <div id="contactUsTabDiv">
        <span>
            Contact Us
        </span>
    </div>
    Append inserts your html here
</div>
After inserts your html here

Solution 7 - Javascript

<div></div>    
// <-- $(".root").before("<div></div>");
<div class="root">
  // <-- $(".root").prepend("<div></div>");
  <div></div>
  // <-- $(".root").append("<div></div>");
</div>
// <-- $(".root").after("<div></div>");
<div></div>    

Solution 8 - Javascript

Imagine the DOM (HTML page) as a tree right. The HTML elements are the nodes of this tree.

The append() adds a new node to the child of the node you called it on.

Example:$("#mydiv").append("<p>Hello there</p>") 

creates a child node <p> to <div>

The after() adds a new node as a sibling or at the same level or child to the parent of the node you called it on.

Solution 9 - Javascript

To try and answer your main question:

why would you use .append() rather then .after() or vice verses?

When you are manipulating the DOM with jquery the methods you use depend on the result you want and a frequent use is to replace content.

In replacing content you want to .remove() the content and replace it with new content. If you .remove() the existing tag and then try to use .append() it won't work because the tag itself has been removed, whereas if you use .after(), the new content is added 'outside' the (now removed) tag and isn't affected by the previous .remove().

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
QuestionEpikView Question on Stackoverflow
Solution 1 - JavascriptJaiView Answer on Stackoverflow
Solution 2 - JavascriptVSri58View Answer on Stackoverflow
Solution 3 - JavascriptalijshView Answer on Stackoverflow
Solution 4 - JavascriptIonică BizăuView Answer on Stackoverflow
Solution 5 - JavascriptI_Debug_EverythingView Answer on Stackoverflow
Solution 6 - JavascriptCode.TownView Answer on Stackoverflow
Solution 7 - JavascriptNateView Answer on Stackoverflow
Solution 8 - JavascriptanuView Answer on Stackoverflow
Solution 9 - JavascriptMichael DurrantView Answer on Stackoverflow