agyanadda@gmail.com

jQuery Add and Remove Elements

jQuery HTML and CSS 1 min read Updated Dec 1, 2026 Topic 12 of 25

Add content

Method Inserts
.append() at the end inside the element
.prepend() at the start inside the element
.after() after the element (outside)
.before() before the element (outside)
$('#list').append('<li>New item</li>');

Create elements safely

const $li = $('<li>').text(userInput).addClass('item');
$('#list').append($li);

Using .text() keeps user input safe.

Remove content

  • .remove() — delete the element itself (and its events)
  • .empty() — delete everything inside it, keep the element

Clone

.clone() copies an element — handy for "Add another row" in forms.

Example

Example — Dynamic to-do list HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>li{margin:4px 0} .del{margin-left:8px;color:crimson;cursor:pointer;border:none;background:none}</style>

<input id="task" placeholder="New task">
<button id="addEnd">Add to end</button>
<button id="addTop">Add to top</button>
<button id="clear">Clear all</button>
<ul id="list"><li>Learn jQuery selectors<button class="del">✕</button></li></ul>

<script>
  $(function () {
    function makeItem() {
      const text = $.trim($('#task').val());
      if (!text) return null;
      $('#task').val('').focus();
      return $('<li>').text(text).append($('<button class="del">✕</button>'));
    }
    $('#addEnd').click(() => { const $li = makeItem(); if ($li) $('#list').append($li); });
    $('#addTop').click(() => { const $li = makeItem(); if ($li) $('#list').prepend($li); });
    $('#clear').click(() => $('#list').empty());
    $('#list').on('click', '.del', function () {
      $(this).parent().fadeOut(200, function () { $(this).remove(); });
    });
  });
</script>

The delete buttons use event delegation (.on with a selector), so new items work too.

Try it Now »

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method adds content at the end inside an element?

Exercise 2 True / False

.empty() deletes the element itself.

Exercise 3 Fill in the Blank

.___() copies an element.

Frequently Asked Questions

Events bound with $('.del').click() only attach to existing elements. Use delegation: $('#list').on('click', '.del', fn).