jQuery Add Elements
Reading and replacing content is useful, but real apps also need to create new elements on the fly, such as adding a row to a list or a card to a feed. jQuery gives you four clear methods for this: append(), prepend(), after(), and before().
Four ways to add content
The trick to choosing the right method is asking one question: do you want the new content inside the element or outside next to it? append() and prepend() work inside, while after() and before() work outside as siblings.
- append() inserts content at the end, inside the selected element.
- prepend() inserts content at the start, inside the selected element.
- after() inserts content right after the selected element, as a sibling.
- before() inserts content right before the selected element, as a sibling.
Adding inside with append and prepend
Say you have a list and you want to grow it. append() drops the new item at the bottom, and prepend() slides it in at the top. Notice that the existing items stay untouched; you are only adding, not replacing.
Growing a list
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="todo">
<li>Write code</li>
</ul>
<script>
$(document).ready(function() {
$("#todo").append("<li>Test code</li>");
$("#todo").prepend("<li>Plan the feature</li>");
// Order is now: Plan the feature, Write code, Test code
});
</script>
</body>
</html>Adding outside with after and before
When the new content should live next to an element rather than inside it, use after() or before(). You can also pass several arguments at once, and jQuery will insert all of them in order.
Inserting siblings around an image
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<img id="pic" src="photo.jpg" alt="A photo">
<script>
$(document).ready(function() {
$("#pic").before("<p>Above the image</p>");
$("#pic").after("<p>Below the image</p>");
});
</script>
</body>
</html>With these four methods you can build up any part of a page dynamically. Practice picking the right one by imagining where you want the content to land relative to the element you selected.
Exercise: jQuery Add Elements
What is the key difference between .append() and .after() when adding content to an element?