what does jQuery data() function do

John picture John · Nov 25, 2009 · Viewed 25.3k times · Source

I have not found what is the use of jquery function data(). Can anyone give me some example of how it can be used?

Answer

Doug Neiner picture Doug Neiner · Nov 25, 2009

Its really useful for associating various objects, strings, arrays, etc with a DOM element. Here is a fun hypothetical use:

$(document).ready(function(){
   $("a").each(function(index, el){
      if(index % 2 == 0) 
         $(this).data('coolColor', 'Orange'); // Set the data
      else 
         $(this).data('coolColor', 'Purple'); // Set the data
   }).click(function(e){
      alert($(this).data('coolColor')); // Retrieve the data
      e.preventDefault();
   });
});

This would select every a tag, and set Orange if its odd, or Purple if its even. This is not the most optimal way to write this code if this is what you really wanted to do, but it does illustrate how to use the .data() function.

You can also use it to store objects:

$("#header").data('headerSettings',{
   color: "red",
   cost:  "$25.00",
   time:  1000
});

Now you could access that data anywhere else on the page:

$("#header").data('headerSettings').color;