Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery .data() work?

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?

like image 825
kazanaki Avatar asked May 04 '10 10:05

kazanaki


People also ask

What is the use of jQuery data () method?

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 .

How read data attribute in jQuery?

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).

What is data method in JavaScript?

The data() method attaches data to, or gets data from, selected elements. Tip: To remove data, use the removeData() method.

How set data attribute in jQuery?

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.


1 Answers

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.

like image 73
Matt Avatar answered Oct 05 '22 05:10

Matt