Web Development

Element Data Storage with jQuery

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:

[cc lang=”javascript”]
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”);

[/cc]

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

[cc lang=”javascript”]
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”);

[/cc]

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *