.detach() vs .remove()

Here we are showing the difference between jQuery .detach() & .remove() functions that are used to remove elements from the document.

.detach() vs .remove()

.detach() is similar to .remove() they will remove the element itself and its inner contnet, the only difference is that .detach() will keep jQuery data, such as events, associated with the removed elements.

DEMO:
  1. Add click event to all <div>
  2. Remove all <div> using .remove()
  3. Re-insert removed <div>
  4. Test if <div> still responds to click
  5. Repeat 2-4 using .detach
HTML
<body>
  <div>A</div>
  <div>B</div>
</body>
jQuery code
// when clicking on div, show text content of div
$("div").click( function() { alert( $(this).text()) } );
Demo
// click on the A or B
A
B

jQuery code
var removed = $("div").remove();
$("body").append(removed);
Demo
// A & B removed & re-inserted but they lost click event after being removed using .remove()
A
B

jQuery code
var detached = $("div").detach();
$("body").append(detached);
Demo
// A & B detached & re-inserted, they still respond to click event after being removed using .detach()
A
B

jQuery manipulation removing