What is the jQuery remove() method?

The jQuery remove() method is used to remove an element or a group of elements from the DOMDocument Object Model. The contents of the element such as the texts and child elements are also removed. With the jQuery remove() method, it is easy to remove an element from the DOM.

Syntax

$([selector]).remove();

Here, the selector could either be a class, element or id selector.

Parameter

The remove() method could take an optional parameter. The parameter can be any of the selectors and can be more than one. The parameter helps to select an element with such a selector.

Example

$("p").remove(".text-success")

The code above will remove any p element with the class .text-success. If there is more than one parameter, then they should be separated by commas. Doing this will delete any element with one or both of these selectors.

See the following snippet.

$("p").remove(".text-success, .bg-light");

Code

Example without parameter

In the example below, we created a button that will remove the p together with its contents. This is achieved because p has the id #elToRem. So when the button is clicked, and since p is the element that matches the id selector, p along with its contents will be removed.

Example with parameter

In the example below, we created a button that when clicked will remove all li elements with class .done.

Example using comma

In this example, we will delete elements that have the classes undone and done using a comma-separated list of parameters.

$("li").remove(".done, .notdone");

Example using jQuery :contains() to delete an element

The :contains() selector selects elements that contain the specified string

Here, we will use :contains() to match an element that has a partially matching parameter.

The element we want to remove is the li element that contains "Art".

Free Resources