jQuery data() method

It is a nice method provided by jQuery which allows us to store arbitrary data in specific DOM elements. This method gives us the facility to store data using key and value as well as to access the data using the specific keys.

In some situations this can be be very useful. Suppose you are displaying some information on a button click retrieving the data from database through an AJAX call, in this case for every button click one AJAX call will be fired. In stead of making repeated AJAX call for the same data one can store it inside a DOM element using jQuery data method and reuse it.

The syntax is:
$(‘selector’).data(key, value);

Suppose you want to store a value ’24’ inside a div having class name ‘myStyle’ with key ‘age’ then it will be like:

For storing: $(‘.myStyle’).data(‘age’, 24);

For retrieving: $(‘.myStyle).data(‘age’); The result will be 24.

We can also store various distinct values.

$(.myStyle).data(‘info’, {age: 24, name: ‘xyz’, addr: ‘abcd’, phone: 22222});

We can access those value like:

$(.myStyle).data(); The result will be {age: 24, name: ‘xyz’, addr: ‘abcd’, phone: 22222}

Or we can also access like:

$(.myStyle).data(‘info’).age; The result will be 24.

$(.myStyle).data(‘info’).name; The result will be xyz.

$(.myStyle).data(‘info’).addr; The result will be abcd.

In case of AJAX calls suppose you have assigned the information retrieved through AJAX call to a variable ‘result’ then you can store it like:

$(.myStyle).data(‘info’, {data: result}); and retrieve $(.myStyle).data(‘info’).result;
Hope you find it helpful.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!