In jQuery, there are three methods for removing elements from the DOM. These three methods are .empty(), .remove(), and .detach(). All these methods are used for removing elements from the DOM, but they all are different.
.hide()
Hide the matched elements. With no parameters, the .hide() method is the simplest way to hide an HTML element:
$(".box").hide();
.empty()
The .empty() method removes all child nodes and content from the selected elements. This method does not remove the element itself, or its attributes.
Note
The .empty() method does not accept any argument to avoid memory leaks. jQuery removes other constructs, such as data and event handlers, from the child elements before removing the elements themselves.
If we had any number of nested elements inside <div class="hai">, they would be removed too.
.remove()
The .remove() method removes the selected elements, including all text and child nodes. This method also removes the data and events of the selected elements.
Note
Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to this, all bound events and jQuery data associated with the elements are removed.
If we had any number of nested elements inside <div class="hai">, they would be removed too. Other jQuery constructs, such as data or event handlers, are erased as well.
.detach()
The .detach() method removes the selected elements, including all text and child nodes. However, it keeps data and events. This method also keeps a copy of the removed elements, which allows them to be reinserted at a later time.
Note
The .detach() method is useful when removed elements are to be reinserted into the DOM at a later time.
Example
<!doctype html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hai!</p>Good <p>Afternoo</p>
<button>Attach/detach paragraphs</button>
<script>
$( "p" ).click(function() {
$( this ).toggleClass( "off" );
});
var p;
$( "button" ).click(function() {
if ( p ) {
p.appendTo( "body" );
p = null;
} else {
p = $( "p" ).detach();
}
});
</script>
</body>
</html>