I am assigning some data to html objects by a jquery I'm creating, the thing is that when I call a method from the plugin, the data I have assigned is not in the object anymore.
It's useful to understand how .data()
works to understand how long the data lives. When you store something with .data()
, it goes into an internal javascript data structure in jQuery. So, in that respect, it's just a javsacript variable and it lives for as long as any other javascript variable lives.
That means once you leave the page, it's entirely gone - just like all other javascript variables.
The other way the data can be removed is if some javascript code specifically removed the data from the data structure. That will normally only happen if you use a jQuery method that intentionally disposes of a DOM object. That can be done with $(elem).remove()
or with $(elem).html("some html)
and any other jQuery methods that remove elements from the DOM. Since those methods remove objects from the DOM, jQuery "cleans up" the .data()
information associated with those elements. The one specific exception to this is .detach()
which removes an element from the DOM, but does not remove it's .data()
info. This is done on purpose to allow you to remove it from the DOM, but preserve it's state presumably so you can put it back in the DOM somewhere else or some time later.
Note: if you remove a DOM element from the DOM without using jQuery functions (such as .removeChild()
or by assigning to .innerHTML
), jQuery will not know that you've removed those DOM elements and the .data()
info will not be cleaned up - it will essentially just be wasting space in memory. It doesn't cause any harm other than consuming some extra memory. If that .data()
info contains references to other javascript or DOM elements, it could cause even larger memory leaks.
If you are using .data()
it creates one case where you want to stick with jQuery methods for anything that can cause DOM elements to be removed. Normally with jQuery, you are free to mix/match plain javascript and jQuery, but this is one case where you shouldn't.
The data using .data()
lives as long as:
jQuery is still in your page. jQuery uses an internal cache for data using .data()
. It's never on the DOM.
as long as the element you bound the data is still around or if removed in the DOM, it was removed by .detach()
you don't reload the page. data stored in .data()
does not persist through page reloads.
From jQuery.data()
documentation:
The
jQuery.data()
method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page. We can set several distinct values for a single element and retrieve them later: