Inserting Content Inside Elements
append()
The append() method inserts new content as the last child inside the selected element, after any content already there. It's the standard way to add new rows, list items, or messages to the end of an existing container.
Example: append()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="list"><li>Item 1</li></ul>
<script>
$("#list").append("<li>Item 2</li>");
</script>
</body>
</html>
prepend()
prepend() adds content at the very beginning of an element, before any of its existing children. Use it when new items -- like the newest message in a chat feed -- need to appear first instead of last.
Example: prepend()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="list"><li>Item 1</li></ul>
<script>
$("#list").prepend("<li>Item 0</li>");
</script>
</body>
</html>
Append Existing Elements
append() can move an existing element into a new position rather than just inserting fresh markup. Since a DOM element can only exist in one place at a time, appending it elsewhere automatically detaches it from its old parent.
Example: Append Existing Elements
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="a"><p id="moveMe">Move me</p></div>
<div id="b"></div>
<script>
$("#b").append($("#moveMe"));
</script>
</body>
</html>
Append Text and HTML
append() can insert plain text or full HTML strings, and jQuery parses HTML strings into real elements before inserting them. This makes it easy to build small chunks of markup on the fly without manually creating each element.
Example: Append Text and HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"></div>
<script>
$("#box").append("<strong>Bold</strong> text");
</script>
</body>
</html>
Build a List
Appending is especially useful for adding new list items one at a time, such as pushing a new li onto a ul each time a user adds a task. Combined with a loop, it's a common pattern for rendering dynamic lists.
Example: Build a List
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="tasks"></ul>
<script>
const tasks = ["Buy milk", "Walk dog"];
tasks.forEach(function(task) {
$("#tasks").append("<li>" + task + "</li>");
});
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: