Question

While studying the jQuery sourcecode I stumbled upon the cleanData-function several times: jQuery.remove() calls it. So do other functions. What is the purpose of calling cleanData before removing the DOM-Element?

Is jQuery's remove()-method superior to a simple(removeChild) like in this fiddle? And if so, why is it so? Does that code lead to memory leaks?

What is the data, which gets cleared before removal? Is there any usecase outside jQuery?

Was it helpful?

Solution

For elements that get event handlers, data, or perform certain other operations from jQuery methods, jQuery will create an entry in jQuery.cache for that element.

The element itself gets a property which holds the key to its entry in jQuery.cache. That's the only thing that links the element and the data.

So when an element is going to be removed, jQuery needs to look up the entry in jQuery.cache by using the key found on the element, and then needs to destroy the related data. If it didn't do this, there would be a memory leak since once the element is gone, there's no way to know that the jQuery.cache data should be removed.

So if you were to use the native .removeChild() to remove and destroy an element, you would be destroying the only link to that data. That's why you must unfortunately use jQuery for all element removal, and why you shouldn't use any other DOM libraries alongside jQuery.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top