jQuery API

.data()

Contents:

.data( key, value ) Returns: jQuery

Description: Store arbitrary data associated with the matched elements.

  • version added: 1.2.3.data( key, value )

    keyA string naming the piece of data to set.

    valueThe new data value; it can be any Javascript type including Array or Object.

  • version added: 1.4.data( obj )

    objAn object of key-value pairs of data to set.

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

We can set several distinct values for a single element and retrieve them later:

$('body').data('foo', 52);
$('body').data('bar', { myType: 'test', count: 40 });

$('body').data('foo'); // 52
$('body').data(); // {foo: 52, bar: { myType: 'test', count: 40 }}

Setting an element's data object with .data(obj) replaces all data previously stored with that element. 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. Until jQuery 1.4.2, jQuery itself used the .data() method to save information about events that have been bound to the element, using a data item named 'events'.

$('body').data('foo', 52);
$('body').data({one: 1, two: 2});

$('body').data('foo'); // undefined
$('body').data(); // {one: 1, two: 2}

Due to the way browsers interact with plugins and external code, the .data() method cannot be used on <object>, <applet> or <embed> elements.

Example:

Store then retrieve a value from the div element.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<div>
    The values stored were 
    <span></span>
    and
    <span></span>
  </div>
<script>
$("div").data("test", { first: 16, last: "pizza!" });
$("span:first").text($("div").data("test").first);
$("span:last").text($("div").data("test").last);
</script>
</body>
</html>

Demo:

.data( key ) Returns: Object

Description: Returns value at named data store for the element, as set by data(name, value).

  • version added: 1.2.3.data( key )

    keyName of the data stored.

  • version added: 1.4.data()

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set:

alert($('body').data('foo'));
alert($('body').data());

The above lines alert the data values that were set on the body element. If nothing was set on that element, an empty string is returned:

Calling .data() with no parameters retrieves all of the values as a JavaScript object. This object can be safely cached in a variable as long as a new object is not set with .data(obj).

Example:

Get the data named "blah" stored at for an element.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { margin:5px; background:yellow; }
  button { margin:5px; font-size:14px; }
  p { margin:5px; color:blue; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<div>A div</div>
  <button>Get "blah" from the div</button>
  <button>Set "blah" to "hello"</button>

  <button>Set "blah" to 86</button>
  <button>Remove "blah" from the div</button>
  <p>The "blah" value of this div is <span>?</span></p>
<script>
$("button").click(function(e) {
  var value;

  switch ($("button").index(this)) {
    case 0 :
      value = $("div").data("blah");
      break;
    case 1 :
      $("div").data("blah", "hello");
      value = "Stored!";
      break;
    case 2 :
      $("div").data("blah", 86);
      value = "Stored!";
      break;
    case 3 :
      $("div").removeData("blah");
      value = "Removed!";
      break;
  }

  $("span").text("" + value);
});

</script>
</body>
</html>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .data() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • Bob
    The data function is very good for caching of elements you know you will access later using jQuery. If you store your data on one hidden element with a very simple selector (for example, $('#myData').data('data')), then the speed gains you will get if you're using a complicated selector will be very significant.

    Instead of using the full selector to access a given element every time, you will use that selector only once, store it to the data element (for example, $('#myData').data('myElement', $('very-complicated-selector'))), and from then on, if you need to access the element, just do $('#myData').data('myElement').

    It's like using the technique of caching a selector while you use it, except that this will permit caching throughout the life of the script, instead of selecting the element, caching, doing work, then coming back later and selecting the element again.
  • It's not obvious from the documentation, but it appears you can store a function (or a reference to a function) using a .data() call:

    // store anonymous function in .data()
    $('#el').data('myFunc', function(text){ alert(text); });
    // alert the string "Hello!"
    $('#el').data('myFunc')('Hello!');

    Are there any drawbacks to doing this?

    I'm no javascript expert, and I'm still not real clear on where jQuery is keeping this data, and how well it cleans up after itself. My concern is primarily if I'm creating and destroying a number of DOM elements on the fly, and attaching functions for use with these temporary elements, will there be any performance issues versus, say, referencing a more permanent function:

    // define permanent function
    window.namedFunc = function(text){ alert(text); };
    // reference permanent function within .data()
    $('#el').data('myFunc', namedFunc);
    // alert the string "Hello!"
    $('#el').data('myFunc')('Hello!');
  • Charlie
    I'm curious--where is this data stored on the element? I'd like to know just in case I have to debug something, and need to see the data object using something like Firebug.
  • Bob
    Actually, there's this good extension to Firebug, called FireQuery. With FireQuery and Firebug, you will be able to see the data stored on a given element using jQuery.
  • Mah
    So is its important that data that should be secured should not be stored in the data object is it? and if they need to be stored, they need to be encrypted right?
  • Zachary
    Here's my problem. Let's say I have the following code:

    <select id="countryList">
    <option value="US">United States</option>
    <option value="GB">Great Britain</option>
    </select>

    and some data on the page in a hidden div:

    <div id="availableCountries" class="hide">{ "US":"US", "GB":"GB" }</div>

    and the following javascript:

    var currentValSelected = jQuery("#countryList").val(),
    countryJSON = jQuery("#availableCountries").data("countryMap", JSON.parse(jQuery("#availableCountries")[0].firstChild.nodeValue.trim());

    If I do: alert(jQuery("#availableCountries").data("countryMap").GB), the code works. But if I replace GB with a variable like: alert(jQuery("#availableCountries").data("countryMap).currentValSelected), the code fails. Returns an undefined value.

    How can I work around this?
  • james
    alert(jQuery("#availableCountries").data("countryMap)[currentValSelected])
  • Zachary
    By the way, I'm not looking for support. I'm just wondering why it fails and what the workaround in this case would be.
  • drummintime
    When you access an Object key via dot notation, javascript only lets you use a string, it won't evaluate a variable. James's example accesses the property via Array notation, and js will evaluate a variable value.

    var myObj={"foo":"bar"}
    var whichProp="foo";

    //all output Bar
    alert(myObj.foo);
    alert(myObj[whichProp]);
    alert(myObj["foo"]);

    //undefined
    alert(myObj.whichProp);
  • enzzo
    I wonder how much amount of data can .data() handle? Is there a limit in terms of kb,MB or Gb? or as RAM permits?