Difference between detach(), remove() and empty() in jQuery

remove() detach() and empty() methos are used to remove elements in the DOM.

remove() in jQuery

Removes all elements in the wrapped set from the page DOM

detach() in jQuery

Removes all elements in the wrapped set from the page DOM but it retaining any bound events and jQuery data.

The detach() method is the preferred means of removing an element that we will want to put back into the DOM at a later time with its events and data intact.

empty() in jQuery

Removes the content of all DOM elements in the matched set.

That meanse empty will remove the content but it not remove the element, so it is same as html('').

CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('.btnRemove').click(function () {
        $('.divRemove').remove();
      });

      $('.btnDetach').click(function () {
        $('.divDetach').detach();
      });

      $('.btnEmpty').click(function () {
        $('.divEmpty').empty();
      });

    });
  </script>
</head>
<body>
  <div class="Container">
    <div class="divRemove" style="height:50px;width:200px;background:Yellow"><span>Remove</span></div>
    <button type="button" class="btnRemove">Remove</button><br />

    <div class="divDetach" style="height:50px;width:200px;background:Green"><span>Detach</span></div>
    <button type="button" class="btnDetach">Detach</button><br />

    <div class="divEmpty" style="height:50px;width:200px;background:Red"><span>Empty</span></div>
    <button type="button" class="btnEmpty">Empty</button><br />

    Please click these three button to test the code.
  </div>
</body>
</html>
DISPLAY
Remove

Detach

Empty

Please click these three button to test the code.

No comments :

Please Give Your Feedback