A small but nice little jQuery tip is to know the difference between the remove()
and detach()
methods. They essentially do the same thing on the surface and will remove the events from the DOM. But there is a subtle difference in that the detach
method will keep all associated data with the element.
It’s perhaps best illustrated with an example.
<div id="el-detach" style="background:red;">detach</div> <div id="el-remove" style="background:red;">remove</div> <script type="text/javascript"> var detach = $('#el-detach').data('el', 'detach'); var remove = $('#el-remove').data('el', 'remove'); console.log($('#el-detach').data()); console.log($('#el-remove').data()); $('#el-detach').detach(); $('#el-remove').remove(); console.log($('#el-detach')); console.log($('#el-remove')); console.log(detach); console.log(remove); console.log(detach.data()); console.log(remove.data()); console.log(detach.attr('style')); console.log(remove.attr('style')); </script>
Below is the output of the console.log
statements.
Object { el="detach"} Object { el="remove"} Object[] Object[] Object[div#el-detach] Object[div#el-remove] Object { el="detach"} Object {} background:red; background:red;
You will notice that even the style
information will stay for both and it’s strictly the data
that is lost. This can lead to a lot of frustrating bugs and is a good thing to be aware of.
If we wanted to just move an element we could just use something like append()
or prepend()
. But if we need to store it for insertion at a later time then the detach()
method becomes very useful.