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?
The . data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr .
Basically jQuery holds the information you store/retrieve with data(name, value)/data(name) and remove with removeData(name) in an internal javascript object named cache . The rest is just a bit of javascript magic to make it work and keep all the associations right.
It should be noted that jQuery's data() doesn't change the data attribute in HTML. So, if you need to change the data attribute in HTML, you should use . attr() instead.
Alternatively, you can also use the jQuery data() method (jQuery version >= 1.4. 3), to get the data-attribute of an element using the syntax like $(element). data(key) . That means in the above example to get the data-id using data() method you can use the statement like $(this).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With