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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.