jQuery - Adding and Removing Elements in jQuery
1. .append()
-
Inserts content inside the selected element, at the end.
$("#box").append("<p>Appended paragraph</p>");
Result (if #box
already had some content):
<div id="box">
Existing content
<p>Appended paragraph</p>
</div>
2. .prepend()
-
Inserts content inside the selected element, at the beginning.
$("#box").prepend("<p>Prepended paragraph</p>");
Result:
<div id="box">
<p>Prepended paragraph</p>
Existing content
</div>
3. .after()
-
Inserts content outside the selected element, after it.
$("#box").after("<p>Paragraph after box</p>");
Result:
<div id="box">Existing content</div>
<p>Paragraph after box</p>
4. .before()
-
Inserts content outside the selected element, before it.
$("#box").before("<p>Paragraph before box</p>");
Result:
<p>Paragraph before box</p>
<div id="box">Existing content</div>
5. .remove()
-
Completely deletes the selected element including its content.
$("#box").remove();
Result:
The entire #box
element is gone from the DOM.
6. .empty()
-
Deletes only the inner content, but keeps the element itself.
$("#box").empty();
Result:
<div id="box"></div>
Quick Summary Table
Method | Action | Example |
---|---|---|
.append() |
Insert inside (end) | $("#box").append("<p>Hi</p>"); |
.prepend() |
Insert inside (start) | $("#box").prepend("<p>Hi</p>"); |
.after() |
Insert outside (after) | $("#box").after("<p>Hi</p>"); |
.before() |
Insert outside (before) | $("#box").before("<p>Hi</p>"); |
.remove() |
Remove element + content | $("#box").remove(); |
.empty() |
Remove content only | $("#box").empty(); |