I have a question related to jQuery .remove() method. Consider this code:
var x;
$("#btn1").click(function() {
x = $("p").remove();
});
$("#btn2").click(function() {
$("body").prepend(x);
});
If the code is checked on click on the button2, the paragraph element is restored.
I heard that remove() and detach() methods are different. How can they be different when remove() itself keeps all jQuery data?
.remove()removes the jQuery internal data about the contained elements fromjQuery.cache. Such data includes custom data set with.data()and the data required by jQuery’s event model..detach()does not remove that data..remove()/.detach()additionally just remove the element(s) from the DOM tree. It’s like removing an item from an array… the item itself does not just magically vanish even if it’s no longer in the array. Especially if you keep a reference to it like you are doing in your code.