Black friday

Save big!

All courses under $5 - for a limited time!

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().

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();
  });