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.3.data( obj )

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

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 }}

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.

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

Additional Notes:

  • Note that this method currently does not provide cross-platform support for setting data on XML documents, as Internet Explorer does not allow data to be attached via expando properties.

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 first element in the jQuery collection, 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 no data at all was set on that element, undefined is returned.

alert( $("body").data("foo")); //undefined
$("body").data("bar", "foobar");
alert( $("body").data("foobar")); //foobar

HTML 5 data- Attributes

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

For example, given the following HTML:

<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

All of the following jQuery code will work.

$("div").data("role") === "page";
$("div").data("lastValue") === 43;
$("div").data("hidden") === true;
$("div").data("options").name === "John";

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

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). Using the object directly to get or set values is faster than making individual calls to .data() to get or set each value:

var mydata = $("#mydiv").data();
if ( mydata.count < 9 ) {
    mydata.count = 43;
    mydata.status = "embiggened";
}

Additional Notes:

  • Note that this method currently does not provide cross-platform support for setting data on XML documents, as Internet Explorer does not allow data to be attached via expando properties.

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:

Support and Contributions

Need help with .data() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .data()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Alex
    > The data is not stored on the element. It's actually stored in $.cache

    Since data is not stored in the element, there's no way to generate html with predefined data accessible with jquery's .data() function (without use of html5 'data-' attributes)? The only way to add data to elements is to use javascript which adds some data lets say on dom ready event? Am I right?
  • When using .data where the value is a function, it seems that the value of `this` inside that function is the containing window. It would be awesome if it were the element instead, but that is not the case.
  • Raphael
    I need to know if a plugin was already initialized. In according to the plugin authoring doc, I should use the data method. So, in my plugin, I put a boolean flag using the data method to do that.
    But what happens if the plugin user put that flag in the tag like "<div data-initialized="true">" ?

    My plugin would be broken, right? Is there some safer way to do that?</div>
  • Joshaven
    First, setting data doesn't set attributes...
    Secondly, you can use a variable that is unlikely to be use by someone else like:
    $('body').data('jQuery_myCoolPlugin', 'initialized')
    if ($('body').data('jQuery_myCoolPlugin') != 'initialized') {/*do something*/}
  • damir
    What about anonymous data? Can't find anything about it, but I've found a few examples using it something like this $.data(this, "example", true);

    Can somebody explain what 3 values do in data? Thanks!
  • Joshaven
    The use of three values is because the first variable is the element that the data is being stored in... try this working example:
    el = $('body').get(0);
    $.data(el, "example", 'Hello World');
    $('body').data('example');
  • daan
    When you store an array using data, you can manipulate that array using normal array functions like array.push(). Saving the manipulated array is not necessary since arrays are passed by reference, not value. It still was something I did not expect..

    e.g.:
    element.data('test').push('new');

  • Declan
    Why doesn't .data() have support for a function as the second argument? It is very similar to .attr() and this functionality (haha) makes sense.
  • // alerts out 'Hello, world!'
    $('body').data('test', alert('Hello, world!'));
    // returns undefined
    $('body').data('test');
  • As Joshaven says, the second argument can be a function. However, the value will be the function, not the return value of the function as is true with .attr(). While I agree that it might be useful to have similar functionality in .data(), I think it's Joshaven's example that prevents it - .data() may be used to store a function which can be called later in execution.

    I'd suggest using .each() in combination with .data() to get the functionality you're looking for.
  • Yourtech
    The second argument can be a function.
    $('body').data('tryMe', function() {return 'Hello World'});
    $('body').data('tryMe')();
  • Justin
    Hello,

    Just wondering if we can add this to part of the documentation?

    We have this:
    .data( key, value )
    .data( obj )

    I think we should also include:
    .data( key, obj )

    I was trying to attach JSON data via .data(obj) but obviously it didn't work out that well.

  • Joshaven
    This can be done through the following:
    json = {one:1, two:2};
    for (key in json){ $('body').data(key, json[key]) }
    $('body').data('two');
    //=> 2
  • If you look at the available types for "value," you'll see that one of them is Object.
  • DB
    Hi,

    I'm getting some odd results that I'm not expecting when using the data function where it is extending objects.

    EG

    var myObj = {foo:"bar"};
    var newobj = myObj;
    $("body").data("params",newobj);
    $("body").data("params").lorem = "ipsum";

    console.log("body",$("body").data("params"));
    //contains foo and lorem as you'd expect
    console.log("newobj",newobj);
    //contains foo as you'd expect but also contains lorem
    console.log("myObj",myObj);
    //contains foo as you'd expect but also contains lorem too.

    Can anyone explain why this is? Is this expected behaviour or a bug? I'd expect it to leave newobj alone.
  • Me
    myObj and newobj both point to the same object.

    See http://api.jquery.com/jQuery.e... for how to copy objects.
  • DB
    I ended up extending the equivalent of newobj with a local object instead. If it helps the code above is the pared-down version of what I was doing, newobj was actually this.savedSearch which was used throughout an object.

    The gotcha here for me was that changing $(body).data("params") also updated newobj. So does the data function create a reference rather than extend the data's object?
  • I am missing documentation on the setData/getData/changeData events. See also http://forum.jquery.com/topic/...
  • Note the subtle change in quotes when trying to access JSON notation from data-attributes. This will not work the other way around.

    Also noteworthy is that it will not update the attributes after you change or set via data(). It is one way traffic only.
  • Geordie Korper
    That it reads from HTML 5 data- attributes but does not write back to them should probably be noted in the Description.