Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery remove function really remove Dom elements?

I am really wondering if jQuery remove function really remove elements from DOM.
First, I looked here but the answers are not convincing.
I encountered this problem when I noticed I am still able to manipulate elements on which I have called remove function.

My code:

<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's going on here!

Actually, this code doesn't remove the #div from the dom, but if I have any data set to the #div, it will be lost. I am pretty confused now about the behaviour of remove function. Can anyone explain this please? DEMO

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

like image 637
ilyes kooli Avatar asked May 23 '12 08:05

ilyes kooli


2 Answers

remove() does indeed remove the element from the DOM.

However in your example, the element has been cached in memory because you assigned it to the div variable. Therefore you can still use it, and append it again, and it will still contain all the events the original did.

If what you say is right, why I loose the data bound to the div so?

If you check the source for remove() you'll see that it calls the internal cleanData function which removes the events and clears the data cache for the element. This is why you lose the information.

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

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

like image 199
Rory McCrossan Avatar answered Sep 22 '22 03:09

Rory McCrossan


had to delete the assigned variable:

delete div;
like image 45
ilyes kooli Avatar answered Sep 26 '22 03:09

ilyes kooli