tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system
Contents:

.data( key, value )

Returns: jQuery
Description: Store arbitrary data associated with the matched elements.

.data( key, value )

version added: 1.2.3
key
A string naming the piece of data to set.
value
Any
The new data value.

.data( obj )

version added: 1.4.3
obj
An 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.

HTML 5 data- Attributes

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

For example, given the following HTML:

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

All of the following jQuery code will work.

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

Note that strings are left intact while JavaScript values are converted to their associated value (this includes booleans, numbers, objects, arrays, and null). 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).

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.
    $("div").data("test", { first: 16, last: "pizza!" });
    $("span:first").text($("div").data("test").first);
    $("span:last").text($("div").data("test").last);
The output of the code above will be:
Example - Full source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="javascript">

  $(document).ready(function(){
    $("div").data("test", { first: 16, last: "pizza!" });
    $("span:first").text($("div").data("test").first);
    $("span:last").text($("div").data("test").last);

  });
  </script>

  <style>
  div { color:blue; }
  span { color:red; }
  </style>
</head>
<body>
  <div>
    The values stored were 
    <span></span>

    and
    <span></span>
  </div>
</body>
</html>

.data( key )

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

.data( key )

version added: 1.2.3
key
Name of the data stored.

.data( )

version added: 1.4

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). 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.
    $("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);
    });
The output of the code above will be:
Example - Full source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="javascript">

  $(document).ready(function(){
    
    $("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>

  <style>
  div { margin:5px; background:yellow; }
  button { margin:5px; font-size:14px; }
  p { margin:5px; color:blue; }
  span { color:red; }
  </style>
</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>

</body>
</html>
Was this information helpful?
   

Comments