The jQuery remove()
method is used to remove an element or a group of elements from the remove()
method, it is easy to remove an element from the DOM.
$([selector]).remove();
Here, the
selector
could either be aclass
,element
orid
selector.
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.
$("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");
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.
In the example below, we created a button that when clicked will remove all li
elements with class .done
.
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");
:contains()
to delete an elementThe :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"
.