Black friday

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

Making jQuery Remove Elements & Their Content: Remove and Empty

Reading time 3 min
Published Dec 20, 2017
Updated Oct 9, 2019

Whenever you wish to remove element jQuery has two methods to offer. The key difference is your intent: you might want to make jQuery remove DOM element as a whole or just wipe out its content.

In this tutorial, we will present the syntax and demonstrate the usage of both methods. Therefore, you will be able to make the best choice and know how to use each correctly.

jQuery Remove Element: Main Tips

  • jQuery has useful methods and selectors which allow you to manipulate and get information from the DOM much more conveniently than by using pure JavaScript.
  • By using special methods, you can make jQuery remove DOM elements and content.

Methods Compared

There are two methods you can use to make jQuery delete elements:

  • .remove() removes the selected element along with its children.
  • .empty() removes only the child items from the selected element.

The syntax for both methods is rather straightforward. We'll see some example snippets in the following sections.

empty()

Here is the syntax for .empty():

$(selector).empty()

To see how it works, you can review a simple example. In it, we make jQuery remove div elements it finds in our code. Click the Try it Live button to see how this works in the code editor:

Example
$("div").empty();

remove()

The syntax for .remove() is only slightly different. As you can see, it accepts additional selectors as parameters for adding extra filters according to which elements should be removed:

$(selector).remove([selector])

To explain the filtering functionality of .remove(), let's take a look at this example:

Example
$("div").remove(".example");

Simply put, the first selector implies that the method should select div elements in the document. If there are no selector arguments, this statement would make jQuery remove div elements from the document completely.

However, the selector argument .example then specifies that out of all the already selected lot, only the elements with the specified class will be removed. It means we don't just make jQuery remove div elements it finds, but filter the matches and only delete part of them.

This feature of the method allows you to be very specific in what elements you want to be removed. Therefore, the function is fairly flexible.

jQuery Remove Element: Summary

  • Making jQuery delete elements is faster and more convenient than using plain JavaScript.
  • By using jQuery remove element, you can delete either the selected element with its children, or its child items only.