What's the best way to store multiple values for jQuery's $.data()? What's the best way to store multiple values for jQuery's $.data()? jquery jquery

What's the best way to store multiple values for jQuery's $.data()?


In 1.4 you can do this:

$('#somediv').data({ one : 1, two : 2, three : 3 });

This is a great way to initialize the data object. HOWEVER, in 1.4.2, bear in mind that using this form will REPLACE ANY existing data on this element. So, if you try this:

$('#somediv').data( 'one', 1 );$('#somediv').data({ two : 2, three : 3 });

You will be blowing away the value for 'one'.

(On a personal note, I think it is a shame since jQuery already makes extensive use of merging objects with its $.extend. Its not clear to me why that wasn't used here.)

UPDATE (suggested by user: @ricka, thank you):

1.4.3 and on, it merges the data (http://api.jquery.com/data/#data-obj):

In jQuery 1.4.3 setting an element's data object with .data(obj) extends the data previously stored with that element. jQuery itself uses the .data() method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

Prior to jQuery 1.4.3 (starting in jQuery 1.4) the .data() method completely replaced all data, instead of just extending the data object. If you are using third-party plugins it may not be advisable to completely replace the element's data object, since plugins may have also set data.


If both approaches are as easy to use in your code, go for storing a single object. It avoids the extra overhead of calling the data() method every time you need a value. This way, you can fetch the mapping object with one call to data(), and then retrieve values from this object as many times as you want without having to call data() again.

The data() method uses objects to map elements to keys/values under the hood, so it does not offer any performance improvements over managing a mapping object yourself.


I'd probably do something like:

var data = $("#div_id").data();   data.foo=1;  data.bar=2;