jQuery Introduction | Manipulating Elements | Removing Elements .remove() .detach() .empty() .unwrap()

Removing Elements

The following methods let you remove selected elements or content.

Method Description
.remove() Removes the selected element from the DOM tree. jQuery data and events associated with the removed element are also removed.
.detach() Removes the selected element from the DOM tree. jQuery data and events associated with the removed element are preserved.
.empty() Removes all child elements of the selected element.
.unwrap() Removes the parent element of the selected element.

.remove() Method

The .remove() method removes the selected HTML element from the DOM tree. At this time, all jQuery data and events associated with the removed element are also removed.

When HTML elements exist as follows:

<p id="one">Hello.</p>
<p id="two">This is devkuma.</p>
<p id="three">Nice to meet you.</p>

Remove the <p> elements whose IDs are one and two.

$("p").remove("#one, #two");

Run code

.detach() Method

The .detach() method removes the selected element from the DOM tree. At this time, jQuery data and events associated with the removed element are not removed and remain preserved.

If the jQuery object returned by .detach() is passed as an argument to a method such as .append() or .prepend(), the removed element can be restored.

When HTML elements exist as follows:

<p class="hello">Hello.</p>
<p>This is devkuma.</p>
<p class="hello">Nice to meet you.</p>

You can confirm that the click event remains even after HTML elements whose class is hello are removed and then restored.

$("p").on("click", function() {
     $(this).toggleClass("wrap");
});
var data = null;
$("#btnDetach").on("click", function() {
    data = $(".hello").detach(); // Removes all elements whose class is "hello".
});
$("#btnRestore").on("click", function() {
    $("p").after(data);  // Adds back all elements removed by detach().
});

Run code

.empty() Method

The .empty() method removes all child elements of the selected element. Unlike .remove() or .detach(), the selected element itself is not removed.

When HTML elements exist as follows:

<div id="container" class="wrap">
    <div>Hello</div>
    <div>This is devkuma.</div>
    <div>Nice to meet you.</div>
</div>

Remove all child HTML elements of the element whose ID is container.

$("#container").empty(); // Removes all child elements of the element whose ID is "container".

Run code

.unwrap() Method

The .unwrap() method removes the parent element of the selected element.

When HTML elements exist as follows:

<div id="container" class="wrap">
    <p>Hello</p>
    <p>This is devkuma.</p>
    <p>Nice to meet you.</p>
</div>
$("p").unwrap(); // Removes the parent element of the <p> elements.

Run code