Episode 11 of 24

Removing Content with jQuery

Learn how to remove, empty, and detach elements from the page with jQuery.

jQuery provides several methods to remove content from the page, each with different behaviour.

remove() — Remove Element Completely

// Remove a specific element
$(".old-banner").remove();

// Remove with a filter
$("p").remove(".outdated");  // Only remove paragraphs with class "outdated"

Important: remove() deletes the element and its data/event handlers.

empty() — Remove All Children

// Remove all content inside an element (the element itself stays)
$(".container").empty();

// Before: <div class="container"><p>Hello</p><p>World</p></div>
// After:  <div class="container"></div>

detach() — Remove but Keep Data

// Remove element but preserve its data and events
let $item = $(".item").detach();

// Later, reattach it
$(".container").append($item);
// Event handlers still work!

remove() vs detach()

  • remove() — permanent deletion, events are lost
  • detach() — temporary removal, events are preserved

Practical Examples

// Delete list item on click
$("ul").on("click", "li", function() {
    $(this).fadeOut(300, function() {
        $(this).remove();
    });
});

// Clear a form
$("#clearBtn").click(function() {
    $("form")[0].reset();  // Reset form fields
    $(".error-messages").empty();  // Clear error messages
});