Vivek
Vivek

Reputation: 11028

Differences between detach(), hide() and remove() - jQuery

What is the functional difference between these three jQuery methods:

Upvotes: 111

Views: 84266

Answers (5)

Zoltán Tamási
Zoltán Tamási

Reputation: 12809

Imagine a piece of paper on a table with some notes written with pencil.

  • hide -> throw a clothe onto it
  • empty -> remove the notes with an eraser
  • detach -> grab the paper in your hand and keep it there for whatever future plans
  • remove -> grab the paper and throw it to the dustbin

The table represents the current DOM space, the paper represents the element, and the notes represent the contents (child nodes) of the element.

A bit simplified and not completely accurate, but easy to understand.

Upvotes: 58

Xuân Nguyễn
Xuân Nguyễn

Reputation: 11

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
    <script>
        $(document).ready(function(){
            var $span;
            $span = $("<span>");
            $span.text("Ngoc Xuan");
            function addEvent() {
                $span.on("click",function(){
                    alert("I'm Span");
                });
            }
            function addSpan() {

                $span.appendTo("body");
            }
           function addButton(name) {
               var $btn = $("<input>");
               $btn.attr({value:name,
                       type:'submit'});
               if(name=="remove"){
                   $btn.on("click",function(){
                       $("body").find("span").remove();
                   })
               }else if(name=="detach"){
                   $btn.on("click",function(){
                       $("body").find("span").detach();
                   })
               }else if(name=="Add") {
                   $btn.on("click",function(){
                       addSpan();
                   })
               }else if(name=="Event"){
                   $btn.on("click",function(){
                       addEvent();
                   })
               }else if (name == "Hide") {
                   $btn.on("click",function(){
                       if($span.text()!= '')
                           $span.hide();
                   })
               }else {
                   $btn.on("click",function(){
                       $span.show();
                   })
               }
               $btn.appendTo("body");
           }
            (function () {
                addButton("remove");
                addButton("detach");
                addButton("Add");
                addButton("Event");
                addButton("Hide");
                addButton("Show");
            })();
        });
    </script>
</body>
</html>

Upvotes: 0

Jason
Jason

Reputation: 141

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.

Example

<div class="content">
<div class="hai">Hai</div>
<div class="goodevening">good evening</div>
</div>
<script>
    $("div.hai").empty();
</script>

This will result in a DOM structure with the Hai text deleted:

<div class="content">
<div class="hai"></div>
<div class="goodevening">good evening</div>
</div>

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.

EXAMPLE

Consider the following html:

<div class="content">
<div class="hai">Hai</div>
<div class="goodevening">good evening</div>
</div>
<script>
    $("div.hai").remove();
</script>

This will result in a DOM structure with the <div> element deleted:

<div class="content">
<div class="goodevening">good evening</div>
</div

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>

For more info, visit: http://www.scriptcafe.in/2014/03/what-is-difference-between-jquery_15.html

Upvotes: 13

Jacob Relkin
Jacob Relkin

Reputation: 163288

hide() sets the matched elements' CSS display property to none.

remove() removes the matched elements from the DOM completely.

detach() is like remove(), but keeps the stored data and events associated with the matched elements.

To re-insert a detached element into the DOM, simply insert the returned jQuery set from detach():

var span = $('span').detach();

...

span.appendTo('body');

Upvotes: 159

Lalit
Lalit

Reputation: 849

hide() sets the matched element's display to none.

detach() removes the matched elements, including all text and child nodes.

This method stores all the data associated with the element and so can be used to restore the element's data as well as event handlers.

remove() also removes the matched elements, including all text and child nodes.

However, in this case only the element's data can be restored, not its event handlers can't.

Upvotes: 14

Related Questions