Where does jQuery store the values of the data()
that it sets to DOM objects?
Is there some kind of variable like jQuery.dataDb
or something, maybe even something private?
Is there any way to gain access to this object?
Where does jQuery store the values of the data()
that it sets to DOM objects?
Is there some kind of variable like jQuery.dataDb
or something, maybe even something private?
Is there any way to gain access to this object?
Ok I figured it out.
jQuery.expando
contains a string that's appended to each element which isjQuery + new Date()
HTMLElement[jQuery.expando]
contains the key to that element'sdata
jQuery.cache[HTMLElement[$.expando]]
contains thedata
on the elementHere is a demo
jQuery gets or sets data in 3 different ways for 3 different type of object.
For DOM element, jQuery first get a unique id, than create a custom property for element called expando:
On the other hand, jQuery has a $.cache object which stores data map for each element, jQuery searches $.cache by expando and get a data map for certain element, getting or setting data in that map:
For custom object(which is not DOM element or window object), jQuery directly set or get a property from that object by name:
At last, for the special window object, jQuery has a special windowData variable in closure to store data for window:
Internally, jQuery creates an empty object called
$.cache
, which is used to store the values you set via the data method. Each DOM element you add data to, is assigned a unique ID which is used as a key in the$.cache
object.