[javascript] .append(), prepend(), .after() and .before()

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);
});

This question is related to javascript jquery append prepend jquery-after

The answer is


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.


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

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


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


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


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

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.


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to append

List append() in for loop ValueError: all the input arrays must have same number of dimensions Append a tuple to a list - what's the difference between two ways? How merge two objects array in angularjs? How to add an element at the end of an array? Appending a list or series to a pandas DataFrame as a row? Can someone explain how to append an element to an array in C programming? How to append elements at the end of ArrayList in Java? Append value to empty vector in R? How to append new data onto a new line

Examples related to prepend

.append(), prepend(), .after() and .before() What's the idiomatic syntax for prepending to a short python list? Most efficient way to prepend a value to an array How to insert element as a first child? How can I implement prepend and append with regular JavaScript?

Examples related to jquery-after

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