Reputation: 6595
I created a to-do list using jQuery (CodePen). In order to remove list items, I used
$(document).on('click', '.item', function() {
$(this).remove();
});
I'm wondering whether it would matter if I used .detach() rather than .remove() (having tried both, functionality seems to be the same). I read the documentation and understand that .remove() removes the element itself as well as everything inside it as well as bound events, while .detach() does the same but keeps jQuery data associated with the removed element.
What would be the ramifications, if any, if I used .detach() and thus maintained associated data?
Upvotes: 1
Views: 73
Reputation: 17654
remove
takes elements out of the DOM
and everything inside it, while detach
removes the DOM
and keeps the data if you want to reinsert it elsewhere :
https://api.jquery.com/detach/
The
.detach()
method is the same as.remove()
, except that.detach()
keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.
use remove()
to delete the element and detach()
to move it somewhere else.
$('#myTodo').remove(); // deletes the todo
const detachedTodo = $('#myTodo').detach(); // removes the todo and keep it in a variable
$('#addButton').on('click', function(){
('#completeTodos').append(detachedTodo) ; // add the removed todo to the completed list
});
Upvotes: 1