jQuery's Data Method - How and Why to Use It

Demo Download

jQuery's data method gives us the ability to associate arbitrary data with DOM nodes and JavaScript objects. This makes our code more concise and clean. As of jQuery 1.4.3 we also have the ability to use the method on regular JavaScript objects and listen for changes, which opens the doors to some quite interesting applications.

The Basics

You can call the data method on a jQuery object, or you can use the $.data() function instead.

// Using the data method:
$("#myDiv").data("key","arbitrary value");

// Using the data function:
$.data($("#myDiv").get(0),"key","arbitrary value");

The data function is a low level implementation, and is actually being used by the method call behind the scenes. The method call is also more convenient, as it allows you to include it as a part of a chain.

Also, notice that you need to pass a DOM element as the first parameter of $.data, and not a jQuery object. This is why in this article, we are going to concentrate on using the method call instead.

When you use the data method, you need to pass two parameters - a key and a value to be stored. The key has to be a string, and the value can be any data structure, including functions, arrays and objects. There is an alternative syntax, in which you pass an object as a single parameter:

// Passing an object:
$("#myDiv").data({"name":"Stevie","age":21});

// This is the same as:
$("#myDiv").data("name","Stevie").data("age",21);

Now that you've inserted your data, you can read it by calling the data method with a single parameter - the key:

var theValue = $("#myDiv").data("age"); // 21

You can access the data everywhere in your script. It doesn't matter what the selector is, as long as it is the same element, you will get the same value you've put in:

// Given that myDiv is the first div in the page:

var theValue = $("div:first").data("name"); // Stevie

$("div:first").click(function(){
    alert($(this).data("age"); // 21
});

As of jQuery 1.4.3 HTML5 data- attributes are also made available via the data method. This means that if you have an element like this:

<img id="img1" data-internal-id="221" width="100" height="100" />

You can access the data-internal-id attribute by just calling $("#img1").data('internal-id'), which is really useful in AJAX applications. We also used this technique in last week's tutorial - Making Better Select Elements with jQuery and CSS3.

Using the Data Method on JavaScript objects

You may find it surprising that you can use the data method on regular JavaScript objects. This functionality has been around for some time, but with jQuery 1.4.3 it opens the doors to some useful applications.

var myObj = {};
$(myObj).data("city","Springfield");

What the snippet above does, is actually create a city property on the object. But why not just set myObj.city = "Springfield" yourself? Because the data method triggers a number of useful events you can listen for:

var progressBar = {};

$(progressBar).bind('setData',function(e,key,value){
    switch(key){
        case "percent":
            $("#progress").width(value+"%");
            $("#percentText").text(value+"%");
            break;

        case "color":
            $("#progress").css("color",value);
            break;

        case "enabled":
            $('#progress').toggleClass("active",value);
            break;
    }
});

$(progressBar).data("enabled",true).data("percent",21).data("color","green");

// You also have easy access to the current values:
console.log(progressBar.enabled);    // true

In the fragment above, we use the data method to create a simple API with which we can update a progress bar on screen. The best part of it is that at any given time you can just take a peek at the progressBar object and get the current values.

There are two other events that are triggered when using the data method on a plain object:

  • getData - triggered before data is read from the object. You can use the return statement within the event handling function to override the value. Can be used to run calculations behind the scenes;
  • changeData - triggered whenever data is set or changed. It is used in the jQuery datalink plugin and allows you to bind a form to a JavaScript object and access the form fields as properties of that object. This way you don't have to deal with reading and setting values, which is quite a burden especially in longer forms. You can see it in action in the demo page.
jquery-data-method-demo.jpg

Behind the Scenes

Internally, jQuery creates an empty object (called $.cache for the curious), which is used to store the values you set via the data method. Each DOM element you add data to, is assigned a unique ID which is used as a key in the $.cache object.

jQuery does not store only user-created data in that cache. It also stores internal information and the event handling functions that you attach with live(), bind() and delegate(). Having centralized data storage makes jQuery's codebase much more robust and bug free, something that we all can benefit from.

To Wrap it Up

The data method is just one of jQuery's numerous utilities, which make the life of the web developer easier. Combined with the rest of the library's abilities, it adds up to a solid foundation we can build upon.

Bootstrap Studio

The revolutionary web design tool for creating responsive websites and apps.

Learn more

Related Articles

Tiarê Balbi

Very good!!!

darkgaro

Nice tutorial, I was wondering about the performance of using data method. Is there any performance penalty ??

Martin Angelov

Getting a value with data() requires a lookup of the DOM element's unique ID (which is defined as an expando property), after which jQuery does a lookup in the $.cache object.

It cannot possibly be as fast as using plain variables, but for attaching data to a specific element this is optimal.

So the short answer is that it depends on what you'll use data for. Performance might become a problem only when using the method in heavy loops. But even then there is a workaround. Just cache the data object:

var obj = $('#myDiv').data();   // you can access data('prop') as obj.prop 

for(var i=0;i<1000000;i++){
    // do something with obj
}

very useful, i have learned a lot

Useful tot,I often forget to use this method...

Giacomo Colddesign

Great article.. thanks for sharing..!

Beben Koben

so usefully, thats briliant idea, thanks a lot master
\m/

Jeremy Carlson

Nice explanation of .data(). Will probably come in handy one day.

Jeremy Hutchings

Ah jQuery ........ the reason to venture off the server when programming :)

i still dont get it? whats the point in doing it this way? so if i write something like:

var myObj = {};
$(myObj).data("title", "My Object");

can i still access it like myObj.title or is it hidden in the jQuery cache? What if I do have some data I don't want to be simply written to the attributes of the tag? Is that when you use this function?

I really don't see the benefit of using this over just a plain javascript object. Am I missing something?

Nick Tulip

nice demo. I would like to see the demo expand into an actual implementation of the progress bar.

William Rouse

I am unfamiliar with the usage of "JSON.stringify(obj).replace". Would you explain what is going on here or point me to a tutorial.
Thanks!

William Rouse

The first button does not work with jQuery 1.61.
What's changed?

Thanks for the tutorial!

There's a missing ending parenthesis on this line:

alert($(this).data("age"); // 21

Svetlana

Thank you for a great article and useful tips, guys!

Adam Fullen

Great example! I was not aware of the events associated with the data() method prior, will be sure to use these now.

One of the important things about the jQuery data() method is that it will acceppt anything that JavaScript does. I have been using it to simplify code writing for event handlers related to cached buttons with unique actions:

var cache = {};
cache.obj1 = $("obj1", document).data('CLICK_METHOD', function1Name);
cache.obj2 = $("obj2", document).data('CLICK_METHOD', function2Name);
cache.objGroup = obj1.add(obj2);

objGroup.on("click", function(e){
  e.preventDefault();
  $(this).data('CLICK_METHOD').call(param);
});

var function1Name = function(param){
  // do function 1 stuff
};
var function2Name = function(param){
  // do function 2 stuff
};

Helpful thanks for the tips.

sticked on this from last two day and this one solved my problem, thx

Missing in this good article the fact that we can save anything in the data mechanism.
Like:
$(this).data("person", {name: 'Dan', age: 33, address: {city: 'Here', state: 'NY'}});
$(this).data("numbers", [3,6,9]);