jQuery API

.append()

.append( content [, content] ) Returns: jQuery

Description: Insert content, specified by the parameter, to the end of each element in the set of matched elements.

  • version added: 1.0.append( content [, content] )

    contentDOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.

    contentOne or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.

  • version added: 1.4.append( function(index, html) )

    function(index, html)A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

You can create content and insert it into several elements at once:

$('.inner').append('<p>Test</p>');

Each inner <div> element gets this new content:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">
    Hello
    <p>Test</p>
  </div>
  <div class="inner">
    Goodbye
    <p>Test</p>
  </div>
</div>

You can also select an element on the page and insert it into another:

$('.container').append($('h2'));

If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
  <h2>Greetings</h2>
</div>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

Additional Arguments

Similar to other content-adding methods such as .prepend() and .before(), .append() also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.

For example, the following will insert two new <div>s and an existing <div> as the last three child nodes of the body:

var $newdiv1 = $('<div id="object1"/>'),
    newdiv2 = document.createElement('div'),
    existingdiv1 = document.getElementById('foo');

$('body').append($newdiv1, [newdiv2, existingdiv1]);

Since .append() can accept any number of additional arguments, the same result can be achieved by passing in the three <div>s as three separate arguments, like so: $('body').append($newdiv1, newdiv2, existingdiv1). The type and number of arguments will largely depend on how you collect the elements in your code.

Examples:

Example: Appends some HTML to all paragraphs.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { background:yellow; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>I would like to say: </p>
<script>
  $("p").append("<strong>Hello</strong>");
</script>

</body>
</html>

Demo:

Example: Appends an Element to all paragraphs.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { background:yellow; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>I would like to say: </p>

<script>
  $("p").append(document.createTextNode("Hello"));
</script>

</body>
</html>

Demo:

Example: Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { background:yellow; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <strong>Hello world!!!</strong><p>I would like to say: </p>
<script>
  $("p").append( $("strong") );
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .append() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .append()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://twitter.com/vitch Kelvin Luck

    I thought append always took multiple arguments and appended them each in turn? Is this usage (which does still seem to work) not supported? Or is it just missing from the documentation?

    e.g. $('#selector').append('one', 'two', $('<div>3</div'));

  • Galymzhan

    I think u can do like this: $(“#selector”).append(‘one’).append(‘two’).append(’3), because API requires only ONE argument.

  • http://twitter.com/NilColor Alexey Blinov

    There is a difference between what you get after appending either. Here is an example:

    $('<p id="t1">t1</p>').appendTo('body').get(0)
    <p id=​"t1">​t1​</p>

    $('body').append('<p id="t2">t2</p>').get(0)
    <body style=​"cursor:​ default;​ ">​

    So if you want to use your newly created element after it was appended – use `.appendTo()`

    P.S. sorry about backslashes… only way to prevent DISQUS from making real paragraphs i found

  • http://edgespan.de/ Alexander Trefz

    But this:

    $(“selector”).append(one, two, three);

    a) works
    b) is faster
    c) and more efficient

    so i think its missing in the Docu.

  • Mike

    Add the sentence:
    To append to the beginning instead of to the end, use prepend instead of append.

  • Alman66

    It isn't stated clear in the description that append() adds elements to the _childNodes_ collection of each of the current elements. Reading the description it could be easily read that append() adds _siblings_ to each of the current elements.

  • Anonymous

    It should be noted that any attempts to append script elements using this method will fail silently:
    $(‘#element’).append(“”);

  • http://www.learningjquery.com/ Karl Swedberg

    Not exactly. Scripts will be evaluated first, and then discarded. So, if you do this: $(‘#element’).append(“alert(‘hello’);”);
    You’ll see the alert.

  • http://www.axeldahmen.de/ Axel Dahmen

    The documentation should state that append(), appendTo(), prepend(), prependTo() and similar jQuery functions silently remove event handlers from a HTML document fragment string.

    So the following code:

    body.append(‘Test‘);

    will result in:

    Test

  • rebus

    Thanks for info – that’s what i’ve been looking for :)

  • http://twitter.com/arken1125 rea talaboc

    Just for more info..
    http://www.catswhocode.com/blog/manipulating-th…

    Hope this helps..

  • http://www.calculateonline.org calculateonlineDotOrg

    What is the return value: the element that was inserted or the new target element ?
    Answer: the element that was inserted (same for appendTo)

  • http://phrogz.net/ Gavin Kistner

    In jQuery 1.4.2, the return value is the receiver, NOT the inserted content. console.log( $('body').append('<div/>')[0].tagName ) // BODY

  • http://edgespan.de/ Alexander Trefz

    You just should use the new Object notation:body.append($(“”, {
    href: “#”,
    click: function(){
    alert(“will work.”);
    }
    });

  • http://edgespan.de/ Alexander Trefz

    You just should use the new Object notation:body.append($(“”, {
    href: “#”,
    click: function(){
    alert(“will work.”);
    }
    });

  • Ben

    How?

    I appended a button with a click function defined but it does nothing. Is it possible?

    $(“div.pagination”).append($(“”, {className: “formbtn pagebtn”, text: “Next »”, click:function()
    {
    alert(“next”);
    console.debug(“next”);
    // currentpage += 1;
    // MGL_ADMIN.render_table(tableid, window[tableid]);
    }
    }));

  • Ben

    How?

    I appended a button with a click function defined but it does nothing. Is it possible?

    $(“div.pagination”).append($(“”, {className: “formbtn pagebtn”, text: “Next »”, click:function()
    {
    alert(“next”);
    console.debug(“next”);
    // currentpage += 1;
    // MGL_ADMIN.render_table(tableid, window[tableid]);
    }
    }));

  • Ben

    It you add an element with events to more than one element (using append), then none of the events work.

    E.g. I have two divs with the class “pagination”. If I append buttons based on the class name, then the clicks do NOT work. However if I append based on an ID, then the clicks DO work.

    This seems counter-intuitive. Could this be supported in future?

    BTW I am using Jquery 1.4.2

    Thanks,

  • Ben

    It you add an element with events to more than one element (using append), then none of the events work.

    E.g. I have two divs with the class “pagination”. If I append buttons based on the class name, then the clicks do NOT work. However if I append based on an ID, then the clicks DO work.

    This seems counter-intuitive. Could this be supported in future?

    BTW I am using Jquery 1.4.2

    Thanks,

  • http://twitter.com/geomorillo Geovanny Morillo

    you have to doit this way
    $('#insert_button').button().live('click', function(event)
    {
    $('#div').append('<button id=”the_button” >Eliminar</button>' );
    };
    $('#the_button').button().live('click', function(event)
    {
    //do something
    }

    it works for sure but some styles may be lost im still looking a workaround

  • Ryan Kinal

    A quick example on how to use the second form of this function:

    If we have HTML:
    <div id=”element”>Hello</div>

    $('#element').append(function(index, html) {
    return ', John';
    });

    Will result in

    <div id=”element”>Hello, John</div>

    Being overly clever with it can result in infinite recursion:

    $('#element').append(function(index, html) {
    return html + ', John';
    });

    I'm not sure exactly why this happens, or what is going on behind the scenes, but I killed a couple browsers that way.

  • http://911-need-code-help.blogspot.com/ Guest

    I am adding tags to the DOM using the following code:

    $(document).ready(function () {
    var s = document.createElement(“script”);
    s.type = “text/javascript”;
    s.src = “http://somedomain.com/somescript.js”;
    $(“head”).append(s);
    });

    While somescript.js loads and I can access the variables inside it, I don’t see the actual tag in the DOM. Is this normal?

  • http://www.learningjquery.com/ Karl Swedberg

    yes, it's normal

  • Syt

    could you elaborate please ?

    When one add a <link> tag, he can see it in the DOM.

    IMO, this inconsistency could be considerated as a bug…

  • NM78

    When i send a site header with php like this:

    <?php
    header(“Content-type: application/xhtml+xml”);
    ?>

    jQuery works, but not the append function. Im using Firefox 3.6.6. Is this a bug?

  • nm78

    More examples:

    1.) $(“div#workbench”).append(“Test”); //<– this works great
    2.) $(“div#workbench”).append(“Test“); //<– this wont work :(

    In the second example i putted into a “strong” tag. Sorry, i dont know how to show the original code. It wont work with every type off html tag.

    What is the reason?

  • http://www.jqueryin.com Corey Ballou

    I found the same to be true, the undocumented functionality is to support an arbitrary number of objects as parameters:

    var $obj = $('<div id=”object1″ />');
    var $obj2 = $('<div id=”object2″ />');
    $('body').append($obj, $obj2);

  • Xvier

    I add new elements (div and Form) with Ajax but then I can not access the created new elements. What is the solution?

    My code is:
    I get the data with ajax and then I put it into .products_group_wrapper DIV
    $('.products_group_wrapper').append(data);

    but then I can submit the form.
    $('input[type="submit"]').click(function(event){…}

    Why I can not access the new elements??

  • Diwakar

    to swap parents of two elements…. is the following code ok?

    $(droppedPanelPar).append($(draggedPanel));
    $(draggedPanelPar).append(replacedPanel);

    Its for swapping the dragged element with the replaced element.

  • Geneariani

    I am not able to append server control tags e.g: “<%” using append. Is it even possible?

  • http://www.learningjquery.com/ Karl Swedberg

    Can you please direct your question to http://forum.jquery.com/ ? Thanks!

  • http://twitter.com/aaronbieber Aaron Bieber

    I really hope that was a Jurassic Park reference.

  • http://www.learningjquery.com/ Karl Swedberg

    All of jQuery's insertion methods use a domManip function internally to clean/process elements before and after they are inserted into the DOM. One of the things the domManip function does is pull out any script elements about to be inserted and run them through an “evalScript routine” rather than inject them with the rest of the DOM fragment. It inserts the scripts separately, evaluates them, and then removes them from the DOM.

    I believe that one of the reasons jQuery does this is to avoid “Permission Denied” errors that can occur in Internet Explorer when inserting scripts under certain circumstances. It also avoids repeatedly inserting/evaluating the same script (which could potentially cause problems) if it is within a containing element that you are inserting and then moving around the DOM.

    My understanding of the intricacies of script injection is pretty limited, so if you'd like to discuss it further, maybe you could post a topic on the jQuery forum.

  • http://twitter.com/timeglider Michael Richardson

    Ah, but is there an easy way to reference what you just added as its own $element? (last child added? something like that?)

  • Frago

    im trying to do this but it seems that cant be done:

    $(“p img”,”.post_text”).append(“

    “).prepend(“

    “);

    any suggestions?

  • JMehring

    I too would like to know this, since I need to be able to bind an event to a newly appended element

  • Mika

    I would like to know this as well.

    I'm pulling data from xml-file, appending each as li-element, now I should be able to bind click, hover etc. to these newly created list elements, and I can't do that…

  • Mika

    …and I found the answer .live()
    :-)

  • http://twitter.com/NathanRijksen Nathan Rijksen

    How exactly does .live() provide you with the element that was just added?

  • http://www.learningjquery.com/ Karl Swedberg

    If you want to reference the element that you added, use .appendTo() instead. console.log( $('<div>').appendTo('body')[0].tagName )
    Or, define a variable and use it later:

    var newDiv = $('<div>').appendTo('body');console.log( newDiv[0].tagName );
  • Bernd Jakoby

    doesnt work with img ??

    html:
    <img id=”loading” src=”images/ajax-loading.gif”>

    jQuery:
    $('#loading').append(“Starting request …”);

    results in:
    <img id=”loading” src=”images/ajax-loading.gif”>Starting request …

  • Iogui

    Bernd,

    You're trying to insert a plain text in an image?
    What are you trying to do?

  • Brad

    I'm having the same issue. I'd like to prepend and append a div tag around an image.

  • http://www.learningjquery.com/ Karl Swedberg

    Huh? If you want to wrap a div around an img, use the .wrap() method:

    http://api.jquery.com/wrap/

  • http://www.learningjquery.com/ Karl Swedberg

    Huh? If you want to wrap a div around an img, use the .wrap() method:

    http://api.jquery.com/wrap/

  • Christian Barthel91

    Can i animate it with fadeIn or something else:

    $(“#something”).append(data).fadeIn(slow);

    I tried it, but it doesn't work. Any ideas?

  • Dz

    Hi!..
    you can try:
    $(“#something”).hide().append(data).fadeIn('slow');

  • Dz

    Hi!..
    you can try:
    $(“#something”).hide().append(data).fadeIn('slow');

  • Dz

    Hi!..
    you can try:
    $(“#something”).hide().append(data).fadeIn('slow');

  • Dz

    Hi!..
    you can try:
    $(“#something”).hide().append(data).fadeIn('slow');

  • Cristi Catea

    how do you append back some text after it has been removed like this: $item.find( “p” ).remove();

  • Cristi Catea

    how do you append back some text after it has been removed like this: $item.find( “p” ).remove();

  • Daveo

    It's a bit tricky, even if you have a reference in memory to it, as all the event code is scrubbed. Rather than remove() use detach(), read up on both though.

  • http://pulse.yahoo.com/_5J6PIB7BIKA7SGDVP4UG2ED5RQ John DOrazio

    I suppose it will work if you have your actual scripting in the html string. If instead you want to dynamically load an external script, it will break. See my comment above http://api.jquery.com/append/#comment-125055898

  • http://pulse.yahoo.com/_5J6PIB7BIKA7SGDVP4UG2ED5RQ John DOrazio

    I do see a <script> tag added in the firebug console… Instead if I try to load dynamically a script as an html string with $.append, such as:

    $(“head”).append(“<script type=”text/javascript” src=”somescript.js”></script>”);

    it doesn't work, it breaks my code. I guess the browser is seeing the script tags within the append as actual script tags, so the closing script tag is actually closing my jquery scripting….
    (P.S. the double quotes in the html string are actually single quotes, they're turned into double quotes automatically…)

  • Guest

    I found that I couldn't fadeOut() an appended element, to my surprise. I had to do $(“body”).find('#' + id).fadeOut(); rather than $('#' + id).fadeOut();

  • Luis22989

    What is the diference between after() and append() ?

  • Ramico

    when appending <button> in IE 8 you don't seem to get it's innerHTML</button>

  • Alexander Wilson

    The Span 1, Span 2,…etc. should be wrapped in 'span' tags, messed up there.

  • thirdhand

    Seems like the return value *isn’t* the element that was inserted, but the container element. I was just bitten by this, as it created a bug in my code that I used a lot of time to figure out. This was the cause.