Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • .empty() vs .remove() vs .detach() - jQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 190
    Comment on it

    .empty() : All the child element of the matched element are removed by this method i.e the element will not be removed only the content of all DOM elements in the matched set are removed.

    .remove() : This method removes the matched element from DOM. It removes the selected elements, including all text and child nodes. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. No copy of removed element is maintained to reinsert the element at later stage.

    .detach() : The detach() method removes the selected elements, including all text and child nodes from DOM. However, the advantage of using this method is that it keeps data and events i.e keeps a copy of the removed elements, which allows them to be reinserted at a later time so it is preferable to use .detach() method instead of .remove() method.

    Program using .empty() vs .remove() vs .detach() method:

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>detach demo</title>
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
     
    <p id = "p1">Hello</p>
    <p id = "p2">Demo</p>
    <div>
    <p id = "p3">Example</p>
    </div>
    <button id="btn1">Attach/detach paragraphs</button>
    <button id="btn2">Remove paragraphs</button>
    <button id="btn3">Empty paragraphs</button>
     
    <script>
    var a;
    $( "#btn1" ).click(function() {
      if ( a ) 
      {
        a.appendTo( "body" );
        a = null;
      } else 
      {
        a = $( "#p1" ).detach();
      }
    });
    $( "#btn2" ).click(function(){
      $("#p2").remove();
     
    });
    $( "#btn3" ).click(function(){
      $("div").empty();
     
    });
    </script>
     
    </body>
    </html>

    On clicking btn1, p1 will be attached to body or detached from DOM thus maintaining copy of removed element. On clicking btn2, p2 will be removed from DOM and all bound events and jQuery data associated with the elements are removed. On clicking btn3, content of div i.e p3 will be removed i.e the element div will not be removed only the content of all DOM elements in the matched set are removed in this case p3.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: