The append and appendTo jQuery methods

With every new release of jQuery more and more features are added. A set of features I use all the time for manipulating the DOM are the prepend() and append() methods. In addition to these methods you also have prependTo() and appendTo(); they vary slightly in the fact that you create your new content first, then choose an element to add it to:

1
2
3
4
5
6
7
8
//Create our content
var appendHTML = "<p>I'm going to be added to the DOM</p>";

//Select our element, then add the html
$("#container").append(appendHTML);

//Create our content, then select the element to append to
$(appendHTML).appentTo("#container");

Prep-end works exactly the same only it adds the content as the first-child of the container rather than the last-child.

With version 1.4 of jQuery came a great addition to both methods;they can now accept a function which returns the index in the current set of elements, and the original HTML string of the element. The addition allows you to loop through a whole set of elements and easily add content to the beginning / end whilst including the original content:

1
2
3
4
5
6
7
8
9
10
11
//Loop through all <p> tags and prep-end "I love jQuery."
$("p").prepend(function(index, html){
    var newHTML = "I love jQuery. " + html;
    $(this).html(newHTML);
});

//Loop through all <p> tags and append ", now with added spice!"
$("p").append(function(index, html){
    html += ", now with added spice!";
    $(this).html(html);
});

Very handy! I’ve put together a little demo to demonstrate this functionality in action.

Loading

Webmentions