56

I want to use .data() in my application. The examples are helpful, but I do not understand however where the values are stored.

I inspect the webpage with Firebug and as soon as .data() saves an object to a dom element, I do not see any change in Firebug (either HTML or Dom tabs).

I tried to look at jQuery source, but it is very advanced for my Javascript knowledge and I lost myself.

So the question is:

Where do the values stored by jQuery.data() actually go? Can I inspect/locate/list/debug them using a tool?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
kazanaki
  • 7,988
  • 8
  • 52
  • 79
  • 3
    you should use firequery: http://firequery.binaryage.com/. `data()` extends the jquery DOM with your data... You should be able to see them fire firequery – meo May 04 '10 at 11:00
  • 2
    Did you look at the minified source? If you did, don't feel bad in the slightest as its completely incomprehensible for just about everyone but the browser. Even the non-compressed source is pretty advanced and often hard to look through. :D – Gordon Gustafson Apr 28 '11 at 16:07
  • I made an example of implementation: Check it, it's very simple: https://jsfiddle.net/andrevlima/zb8oo0p0/24/ storeData(element, data) //-> Register new data storeData(element) //-> Get data registered – André Vinícius Mar 18 '17 at 19:04

3 Answers3

40

Have a look at the source for it.

From a quick glimpse, it looks like it's storing the data in that cache variable that is created on line 2.

Edit:

Here's a quick demo that finds the data in the cache: http://jsfiddle.net/CnET9/

You can also dump $.cache to your console and explore it manually.

Matt
  • 43,482
  • 6
  • 101
  • 102
  • Nope, that cache variable is just some jQuery internal stuff. The data is in fact attached to a DOM element. BTW: Didn't he point out that the jQ source code wasn't helpful? So why point him there? – selfawaresoup May 04 '10 at 11:17
  • 6
    @Techpriester - You are incorrect, it **is** stored on the cache variable, using a key that represents your DOM element, it is **not** stored on the DOM element itself. – Nick Craver May 04 '10 at 11:19
  • 6
    Because I assume he's looking at the jQuery source directly, not the nicely organized source on GitHub. – Matt May 04 '10 at 11:19
  • You can find it quickly using $.cache[domElement[$.expando]]: http://jsfiddle.net/N8e4W/ – Nick Spacek Jan 18 '12 at 14:34
  • Hey Matt, can you tell me whether it is possible anyhow to edit the `data` attribute through Firequery, like we can do by double clicking on normal element attributes in Firebug and edit them in-place? In Firequery, double clicking on the `data` parts takes me to a blank screen in Firebug.. – SexyBeast Mar 16 '13 at 22:06
  • So I stuck some data on the `body` element in a document, and sure enough, the data is in `$.cache[1].data.info`. But how does it know it goes with the `body` element? The only possible identifier in that variable name is the numeral `1`, and `$(*).eq(1)` of course returns the `head` element, so it's not that. – 75th Trombone Sep 17 '13 at 15:43
  • @75thTrombone because jQuery throws the cache index in an attribute (using "expando" as the key) on the raw body element. Expando is a random value e.g. `jQuery19108083871426060796` - you can see the cache id by looking at element[jQuery.expando]. So in your case, `$.cache[$('body')[0][jQuery.expando]].data` - see [Data.js](https://github.com/jquery/jquery/blob/master/src/data/Data.js) source to see the magic. – Matt Sep 17 '13 at 17:26
  • @75thTrombone further, the lookup you're asking about doesn't seem to be possible (deriving the DOM element from the cache). The lookup is always the other way around: element -> cache – Matt Sep 17 '13 at 17:28
  • 4
    `$.cache` seems gone since jQuery 2.0. – Pang Jun 01 '16 at 09:41
  • @NickCraver how is the connection made between the DOM element and the data Key, I don't see any jquery key attributes on the DOM elements that have data assigned to them – buga Aug 30 '22 at 10:13
7

You seem to have gotten the answer to where, but here is a bit on the how. There are some rules you should be aware of before using this.

ADDING

Adding variables using the object returned from $('.selector').data() works because the data object passes by reference, so anywhere you add a property, it gets added. If you call data() on another element, it gets changed. It is what it is what it is...

var oData = $('#id').data();
oData.num = 0;
oData.num == $('#id').data().num; // true

Adding an object places a object inside of the data object, as well as "extends the data previously stored with that element." - http://api.jquery.com/data/#entry-longdesc

That means that adding an obj to dataObj becomes

oData.obj = {};    
oData === { /*previous data*/, obj : { } }

Adding an array does not extend the data previously stored, but doesn't behave the same as a simple value either...

USING

If you have simple values stored, you can place them into variables and do what you want with them without changing the data object.

however

if you are using an object or array to store data on an element, beware!

Just because you store it to a variable does not mean you are not changing data value. Just because you pass it to a function does not mean you are not changing data values!

It is what it is what it is.. unless it's simple.. then it's just a copy. :p

var data             = $("#id").data();  // Get a reference to the data object 
data.r_redirect      = "index.php";      // Add a string value
data.num             = 0;                // Add a integer value
data.arr             = [0,1,2];          // Add an array
data.obj             = { a : "b" };      // Add an object

                                         // but here is where the fun starts! 

var r_redirectString = data.r_redirect;  // returns "index.php", as expected.. cool
r_redirectString     = "changed"         // change the value and the compare :
data.r_redirect      == r_redirectString // returns false, the values are different

var oArr             = data.arr;         // Now lets copy this array
oArr.push(3);                            // and modify it.
data.arr            == oArr              // should be false? Nope. returns true.
                                         // arrays are passed by reference.
                                         // but..

var oObj             = data.obj          // what about objects?       
oObj["key"]          = "value";          // modify the variable and
data.obj["key"]     == oObj["key"]       // it returns true, too!

So, resources..

What's the best way to store multiple values for jQuery's $.data()? https://stackoverflow.com/a/5759883/1257652

Community
  • 1
  • 1
Brett Weber
  • 1,839
  • 18
  • 22
4

You can inspect it by just calling .data() without params, like this:

$("div").data("thing", "value");​​​​​​
console.log($("div").data());
//or...
console.log($.data($("div").get(0)));

As for the "where", it's stored in a global jQuery cache object under a key that represents your element. Calling .data() really returns jQuery.data(yourDomElement), or tack on a key to that if you called for a specific value from it.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155