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

Note: Setting an element's data object with .data(obj) replaces all data previously stored with that element, including events that have been bound to the element.

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

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

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.

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.
  • It'd be nice if one could do something like:

    $("#test").data("variable")++;
  • Bob
    You could do something like that. For example, you could initialize your data like so:

    $("#test").data("variable", {variable: 0});

    Then, you could do something like this:

    $("#test").data("variable").variable++;

    That will work as expected. Of course, now you have to access that value using:

    $("#test").data("variable").variable;

    Instead of just using .data("variable"), but depending on what is more convenient to you it might not be a problem.
  • yasarbayar
    Is there anyway to attach a custom event listener on a value of data. Ex:

    $.data('status')
    .bind('change',function(){
    $('#status').html($.data('status))
    });

    Or is there any other way that i could achieve the behaviour described above ?
  • Perhaps there should be a warning about .data() not working on object/embed tags in jQuery 1.4 (even if they don't contain java applets).
  • I too am confused about the presence of event handlers on the data object. I have used data() in the past as a way to associate some data with the UI representation of that data. GUI toolkits often give you this sort of extra property (like "Tag" in .NET WinForms). I do like the idea of being able to get or set all event handlers through this kind of object, but I'm unclear why they, and not other, properties are included. And mainly I'm just concerned that I will overwrite event handlers when I use "data" for what I thought was its intended purpose -- to allow a developer to associate some bit of model data with its UI. For example, in a handler, I might find out which behind-the-scenes object a particular element represents because I cached a reference to it (or an ID, etc), in the data property.
  • question
    The following moment is very interesting. Can anybody comment it?

    // Alert doesn't work
    $('<div>click me</div>').click( function(){alert('where?')} ).data( {key: 'val'} ).appendTo( 'body' );
    //Alert
    $('<div>click me!</div>').click( function(){alert('there!')} ).data('key','val').appendTo( 'body' );

    Why is it happened?
  • That's definitely strange behavior. If you swap the order of the method calls, it works as expected:

    $('<div>click me</div>')
    .data( {key: 'val'} )
    .bind("click", function(){alert('where: '+$(this).data("key"))} )
    .appendTo( 'body' );

    But adding data after binding causes the alert to fail:

    $('<div>click me</div>')
    .bind("click", function(){alert('where: '+$(this).data("key"))} ) // doesn't work
    .data( {key: 'val'} )
    .appendTo( 'body' );
  • question
    Ok, I've understand the cause of it:

    If we set an element's data using an object, all data previously stored with that element is overridden. Because this data includes events that have been bound to the element, we should use caution when setting .data() with an object.
  • Sebastian B.
    I agree to helianthus.

    But special data properties like .events should IMO rather be hidden from data() methods. Or are there use cases where .events needs to be read/written?

    If yes .events (and any other special properties, if there are any) should be documented here (along with some use cases) to make them part of the official, stable API.
  • Senamion
    I used $.data(this) to get the unique id of an element. With 1.4 is not possible, what can i use instead?