← Back to Chapters

jQuery Remove Elements

? jQuery Remove Elements

? Quick Overview

jQuery allows you to remove elements from the DOM using two main methods: remove() and empty().

? Key Concepts

  • remove() removes the element and all its children
  • empty() removes only the child elements

? Syntax / Theory

? View Code Example
// Removes the selected element and its children
$(selector).remove();
// Removes only the children of the selected element
$(selector).empty();

⚡ Interactive Lab

? Interactive Container

I am a child element inside the box.

(If I disappear but the blue border remains, you used empty!)

⚙️ Code Example 1: Remove or Empty a Box

? View Code Example
// HTML structure and jQuery remove/empty actions
<div id="box">
<h3>This is a box</h3>
<p>It has some content inside.</p>
</div>

<button onclick="$('#box').remove()">Remove Box</button>
<button onclick="$('#box').empty()">Empty Box</button>

This is a box

It has some content inside.

⚙️ Code Example 2: Remove List Items

? View Code Example
// Removing individual or all list items
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<button onclick="$('#myList li:last').remove()">Remove Last Item</button>
<button onclick="$('#myList').empty()">Empty List</button>
  • Item 1
  • Item 2
  • Item 3

? Live Output / Explanation

  • remove() deletes the element completely
  • empty() keeps the container but clears its content

? Use Cases

  • Clearing dynamic lists
  • Removing unused UI components
  • Resetting page sections

✅ Tips & Best Practices

  • Use remove() when elements are no longer required
  • Use empty() to reuse containers
  • Store removed elements if needed later

? Try It Yourself

  • Remove a heading dynamically
  • Clear a table body using empty()
  • Toggle between hide and remove