Adding new content to your website dynamically is one of the most exciting parts of jQuery. Whether you're adding a new comment to a list, a new row to a table, or a loading message, jQuery provides four methods that let you insert content with pinpoint accuracy.
There are four methods used to add new content. The difference between them is **where** they place the content relative to the target element.
| Method | Where it adds content... |
|---|---|
append() |
At the **end** of the selected elements (inside). |
prepend() |
At the **beginning** of the selected elements (inside). |
after() |
**After** the selected elements (outside). |
before() |
**Before** the selected elements (outside). |
$("p").append(" <b>Appended text</b>.");
$("p").prepend("<b>Prepended text</b>: ");
$("img").after("<p>This text comes AFTER the image.</p>");
$("img").before("<p>This text comes BEFORE the image.</p>");
Before adding an element, you need to create it. There are three common ways to create new elements in jQuery:
// 1. Using an HTML string
var txt1 = "<p>Text created with HTML.</p>";
// 2. Using a jQuery object
var txt2 = $("<p></p>").text("Text created with jQuery.");
// 3. Using pure JavaScript DOM nodes
var txt3 = document.createElement("p");
txt3.innerHTML = "Text created with DOM.";
// Finally, add them to the page
$("body").append(txt1, txt2, txt3);
Here is how you would add a new item to a list when a button is clicked.
$("#addBtn").click(function() {
var itemValue = $("#inputArea").val();
if (itemValue != "") {
$("ul").append("<li>" + itemValue + "</li>");
$("#inputArea").val(""); // Clear input
}
});
append() or prepend() for
lists, sub-menus, and message logs. Use before() and after()
for inserting separators, advertisements, or informational blocks.
append/prepend go inside the tag;
after/before go around the tag..html()
content..on()) to handle clicks.