🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

Removing Child Elements With jQuery .empty()

Reading time 2 min
Published Jan 18, 2018
Updated Oct 2, 2019

jQuery empty: Main Tips

  • The jQuery .empty() method removes all descendant nodes from selected DOM elements.
  • All strings of text are also considered child elements and thus removed.
  • To remove elements completely, use the .remove() method. To remove them but keep their data and event handlers, use .detach().
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
Udemy
Pros
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

Usage of jQuery .empty() Explained

The .empty() jQuery method removes the children and nodes of the specified elements. All you need to do is specify a selector to match the target elements:

$(selector).empty();

Check the example with the selector defined as <p> below:

Example
$(document).ready(() => {
	$("button").click(() => {
	    $("p").empty();
	});
});

Note: if you make jQuery remove all children elements, nested elements will be deleted as well.

Differences Between jQuery .empty(), .detach() and .remove()

There are three methods used for removing elements in jQuery: .empty(), .detach() and .remove(). A beginner might find it a bit confusing. You will find the differences of these methods explained in the table below:

Method Definition
.empty() Removes the content and child elements from the selected element, but does not remove the element itself.
.detach() Removes all child elements with the selected element, but keeps data and event handlers, so you may re-add them at a later time.
.remove() Removes all child elements, data and events with the selected element.

Compare the methods in the example below:

Example
$(document).ready(function () {

  $("button.btn-remove").click(function () {
    $("#textbox1").remove();
  });

  $("button.btn-empty").click(function () {
    $("#textbox2").empty();
  });

  $("button.btn-detach").click(function () {
    $("#textbox3").detach();
  });