Does jQuery function really remove Dom elements?

I'm really curious if the jQuery remove function really removes elements from the DOM.
First, I looked here , but the answers are not convincing.
I ran into this problem when I noticed that I can still manipulate the elements on which I called the remove function.

My code is:

<div id="container"> <div id="div"> This is a div </div> </div> var div = $('#div'); $('#div').remove(); $('#container').append(div); 

Note: My question is not how to solve this? but I want to understand what is happening here!

Actually, this code does not remove #div from dom, but if I have data strong> set to #div, it will be lost. Now I'm pretty confused about the behavior of the delete function. Can someone explain this please? Demo

I am convinced that the div variable is not only a clone of the dom element, it is a reference to it, because when I manipulate the div variable (e.g. div.html('something') ), the div inside the DOM is updated.
Or am I wrong?

+8
javascript jquery dom html
source share
2 answers

remove() really removes the element from the DOM.

However, in your example, the element was cached in memory because you assigned it to the div variable. Therefore, you can still use it and add it again, and it will still contain all the events that the original made.

If you say correctly, why am I losing data bound to a div like that?

If you check the source for remove () , you will see that it calls the internal function cleanData , which removes events and clears the data cache for the element. That is why you are losing information.

If you want to remove an element from the DOM, but save the elements, use detach() instead.

Here's a script to show the difference: http://jsfiddle.net/2VbmX/

+14
source share

had to delete the assigned variable:

 delete div; 
+2
source share

All Articles