Element Data Storage with jQuery

  • Avinash
  • 2
  • Nov 28, 2011
  • Web Development

In earlier article I have explained about storing the data in HTML element using MooTools. Now I am going to cover the same feature with the jQuery.

So now lets start with the Element Storage in jQuery.

With these type of storage we gets free from memory leak. These data will gets removed when we remove that element from the DOM or user leaves/refresh the page.

We can store the data using key value pair in any DOM element. We can store anything like single variable, array, object, etc.

Here are the two methods to achieve this:

jQuery.data()

This method takes three parameter.

1) Object of Element
2) Key
3) Actual value which we want to store

Basic Example:

jQuery.data(element, key, value) // Set the value jQuery.data(document.body, "test", "100"); var obj = $("id_of_element"); jQuery.data(obj, "test2", "1000"); // Get the value // Will return "100" jQuery.data(document.body, "test"); // Will return "1000" jQuery.data(obj, "test2");
  jQuery.data(element, key, value)
 
  // Set the value
  jQuery.data(document.body, "test", "100");
  var obj = $("id_of_element");
  jQuery.data(obj, "test2", "1000");
 
  // Get the value
 
  // Will return "100"
  jQuery.data(document.body, "test");
 
  // Will return "1000"
  jQuery.data(obj, "test2");

.data()

This way is almost same as previous one, except in this method we will call with reference of object of an element.

So this methos will need only two parameters.

1) Key
2) Value which we want to store

Basic Example:

elment_obj.data(key, value) // Set the value document.body.data("test", "100"); var obj = $("id_of_element"); obj.data(obj, "test2", "1000"); // Get the value // Will return "100" document.body.data("test"); // Will return "1000" var obj = $("id_of_element"); obj.data("test2");
  elment_obj.data(key, value)
 
  // Set the value
  document.body.data("test", "100");
  var obj = $("id_of_element");
  obj.data(obj, "test2", "1000");
 
  // Get the value
 
  // Will return "100"
  document.body.data("test");
 
  // Will return "1000"
  var obj = $("id_of_element");
  obj.data("test2");

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: