As explained by the documentation, $.detach()
retains the associated jQuery data whereas $.remove()
removes that data. This data contains things like the bound events, the animation queue and whatever you manually added with $.data()
.
In your original example, you should be able to notice the difference in the following scenario:
- Click the paragraph.
- Click the button.
- Click the paragraph again.
For #p1
and #btn1
, clicking the paragraph the second time will still trigger the click handler and bump the font size. This is because the event handler is stored in the data and is retained by detach()
. Thus, when reattaching it to the DOM, the handler is still bound.
For #p2
and #btn2
however, the event handler is removed by remove()
and clicking on the paragraph the second time won't do anything.
Side note: you don't need to call detach()
when you're immediately appending it to the DOM again. detach()
may be interesting if you want to store the element in a variable for a while until it needs to be re-appended (with the same data and behaviour). remove()
is commonly used to just destroy an element, also cleaning up any associated data.