jQuery API

jQuery.data()

Contents:

jQuery.data( element, key, value ) Returns: Object

Description: Store arbitrary data associated with the specified element. Returns the value that was set.

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

    elementThe DOM element to associate with the data.

    keyA string naming the piece of data to set.

    valueThe new data value.

Note: This is a low-level method; a more convenient .data() is also available.

The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page. We can set several distinct values for a single element and retrieve them later:

jQuery.data(document.body, 'foo', 52);
jQuery.data(document.body, 'bar', 'test');

Note: 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>var div = $("div")[0];
    jQuery.data(div, "test", { first: 16, last: "pizza!" });
    $("span:first").text(jQuery.data(div, "test").first);
    $("span:last").text(jQuery.data(div, "test").last);</script>

</body>
</html>

Demo:

jQuery.data( element, key ) Returns: Object

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

  • version added: 1.2.3jQuery.data( element, key )

    elementThe DOM element to query for the data.

    keyName of the data stored.

  • version added: 1.4jQuery.data( element )

    elementThe DOM element to query for the data.

Note: This is a low-level method; a more convenient .data() is also available.

Regarding HTML5 data-* attributes: This low-level method does NOT retrieve the data-* attributes unless the more convenient .data() method has already retrieved them.

The jQuery.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(jQuery.data( document.body, 'foo' ));
alert(jQuery.data( document.body ));

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 jQuery.data(element) retrieves all of the element's associated values as a JavaScript object. Note that jQuery itself uses this method to store data for internal use, such as event handlers, so do not assume that it contains only data that your own code has stored.

Note: 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, div = $("div")[0];

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

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

</script>

</body>
</html>

Demo:

Support and Contributions

Need help with jQuery.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 jQuery.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
  • http://www.google.com/profiles/VanAndelM VanAndelM

    Note that if you use $(this) within the .data() method, it will refer to the data itself – NOT your original jQuery object.

    For instance, let’s say you wanted to dynamically store an input/textbox element’s original value using data() and you wrote something like this:

    $(‘input.MyElem’).data( ‘MyData’ , $(this).val() );

    This won’t work because $(this).val() refers to the value of the 'MyData' data within $('input.MyElem')… it does NOT refer to your original $('input.MyElem') selection. In other words, you are essentially setting MyData equal to itself (even if you’re declaring it for the first time).

    To achieve the original goal of storing the default textbox value as data, you need to wrap the .data() in an .each() method so that the original selection can be temporarily stored in a variable. Hence, the above code would need to be adjusted like so:

    $(‘input.MyElem’).each(function(){
    var MyElem = $(this);
    MyElem.data(‘MyData’,MyElem.val());
    });

    • Anonymous

      jQuery.proxy( function(){$('input.MyElem').data( 'MyData' , $(this).val() )}, this );

  • http://truefalsemaybe.com Tom Longson

    hiddenhancement!

    var foo = {};
    jQuery.data(foo, “narf”, “point”);
    jQuery.data(foo, “narf”);​​​​​​​​​​​​​​ //”narf”

    • http://www.learningjquery.com/ Karl Swedberg

      Nice one — except it will return “point,” not “narf.”

  • Lweek

    If I clone element, it seems that it doesn't clone data within? I tried clone element using jQuery UI drag/drop but I need to clone data as well. Any idea? Thanks in advance.

  • Anish

    in http://paulirish.com/2009/perf/ in the 51st slide, it says:

    $.data(elem, key, value); is 10 times faster than $(elem).data(key, value);

    in this page, i saw:
    Note: $.data() is a low-level method; you should probably use .data() instead.

    can someone please confirm whether $.data() is faster than .data(), & also which is better to use?

  • silly8888

    Does this play with garbage collection? I understand that it stores the data in some internal object. What happens to the data when the element is garbage collected by the browser?

  • http://twitter.com/timmolendijk Tim Molendijk

    I am missing documentation on the setData/getData/changeData events. See also http://forum.jquery.com/topic/setdata-getdata-events-should-be-capable-of-overriding-data-s-default-behavior-but-how

  • Dilascio2781

    can you give html attributes to jquery data? like href? stuff like that?

  • Nekcih

    I'm using $.data(myElement, 'key', 'val'); which works fine. I can store and retrieve data. When the javascript context changes, the data is lost. Has anyone else had issues with this? I'm wondering if it's related to appendTo() operating on myElement. I can retrieve the data after performing appendTo() but not after javascript execution leaves the function. Any ideas?

    • http://twitter.com/cdutson Corey Dutson

      Yeah the $.data isn't great if you're going in and out of context. I've found that setting it to the actual element with $('#thing').data() is more dependable. Sadly though you suffer a performance hit.

  • Jquery_master

    .data() is faster than $.data()

  • http://brunomiranda.com/ Bruno Miranda

    Is there a limit to how much it can be stored? I am running into issues when trying to store a lot of data. Does anyone know what limits I should be looking for?