jQuery Remove

jQuery Remove Elements

If you need to delete elements or clear out content dynamically, jQuery makes it painless.

This is highly useful for removing error messages, dismissing pop-ups, or resetting forms.


The Two Removal Methods

jQuery contains two primary methods to remove elements and content:


The remove() Method Example

The remove() method deletes the element itself from the DOM.

If you select a <div> and call remove(), the <div> and everything inside it vanishes forever.

Remove Example:

$("button").click(function(){
  $("#div1").remove();
});

The empty() Method Example

The empty() method only deletes the internal contents of an element.

The parent element stays on the page, ready to be filled with new data later.

Empty Example:

$("button").click(function(){
  $("#div1").empty();
});

Filtering the Elements to be Removed

The remove() method also accepts one parameter, which allows you to filter the elements.

The parameter can be any standard jQuery selector syntax.

For instance, you can choose to remove only paragraphs that have a specific class.

Remove with Filter:

// Removes all 

elements that have class="test" $("p").remove(".test");

This makes precise clean-ups very efficient.

You can even separate multiple filters with a comma: $("p").remove(".test, .demo");


Exercise 1 of 1

?

Which method clears out the text and child elements inside a container, but leaves the container itself on the page?