0
votes

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?

1
These are two completely unrelated questions. Please open a separate one for each. Also, the first one needs more detail. What exactly do you want to know about the javascript: keyword.Philipp
What's your actual question?Henrik Andersson
@Philipp if u can answer this plz help me.That's what i neededMaizere Pathak
@MaizerePathak I will answer you after you did what I told you to do.Philipp

1 Answers

3
votes

.remove() removes the jQuery internal data about the contained elements from jQuery.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.