How to Append Content to an Element in jQuery
This article explains how to insert content at the end of a selected element using jQuery. You will learn the primary method used for this task, review its syntax, explore practical code examples, and understand how it differs from alternative jQuery DOM manipulation functions.
The .append() Method
The primary jQuery method to append content to the end of an element
is .append(). When called on a target element,
.append() inserts the specified content inside that
element, as its last child.
Basic Syntax
$(selector).append(content);selector: The target element that will receive the new content.content: The HTML string, DOM element, text, or jQuery object you want to insert.
Practical Example
Consider the following HTML structure:
<div id="container">
<p>First paragraph</p>
</div>To add a new paragraph to the end of #container, use the
.append() method:
$('#container').append('<p>Second paragraph</p>');After execution, the resulting HTML becomes:
<div id="container">
<p>First paragraph</p>
<p>Second paragraph</p>
</div>Passing Multiple Arguments
The .append() method can accept multiple elements or
strings simultaneously to insert them in sequence:
var item1 = "<li>Apple</li>";
var item2 = "<li>Banana</li>";
var item3 = document.createElement("li");
item3.innerText = "Orange";
$("ul").append(item1, item2, item3);The Alternative:
.appendTo()
jQuery also provides the .appendTo() method, which
performs the exact same task with inverted syntax. Instead of targeting
the parent first, you target the content to be inserted:
$('<p>Second paragraph</p>').appendTo('#container');Use .append() when you are working directly with the
container element, and use .appendTo() when you have
created content that needs to be attached to a designated target.
Difference Between
.append(), .prepend(), and
.after()
.append(): Places content inside the target, at the end (as the last child)..prepend(): Places content inside the target, at the beginning (as the first child)..after(): Places content outside the target, immediately following it as a sibling.