0

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?

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
Maizere Pathak
  • 303
  • 1
  • 9

1 Answers1

3

.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.

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • i edited my post and i got it closed why? – Maizere Pathak Feb 06 '13 at 17:12
  • @MaizerePathak It was closed before you edited (because it had two unrelated questions in a single post). Now it may be reopened. Try to comment to some of the people above, mentioning their usernames with @, maybe they'll vote to reopen too. – bfavaretto Feb 06 '13 at 17:20