The jQuery.data() method
Example
Store and then retrieve data on a div element
<
div
The stored value is <
span
span
and <
span
span
div
<script$(function(){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
Try it »
Definition and Usage
The $.data() function is used to store and retrieve data on a specified element and returns the set value.
Tip: 1. This is a low-level method; the .data() method is more convenient to use.
2. Data stored and retrieved through the data() function is temporary; once the page is refreshed, previously stored data will be removed.
3. This method currently does not provide cross-platform support for setting on XML documents; Internet Explorer does not allow attaching data via custom attributes in XML documents.
Syntax
Usage 1
$
.data( element, key, value )
Note: 1. Data stored and retrieved through the data() function is temporary; once the page is refreshed, previously stored data will be removed.
2. undefined is an unrecognized data value. Calling jQuery.data( el, "name", undefined ) will return the corresponding "name" data, equivalent to jQuery.data(el, "name" ).We can set different values on an element and retrieve those values:
jQuery.data(document.body, 'foo', 52); jQuery.data(document.body, 'bar', 'test');Usage 2
$
.data( element, key )
We can set different values on an element and retrieve those values:
alert(jQuery.data( document.body, 'foo' )); alert(jQuery.data( document.body ));
Parameters Description element Element type: The DOM object on which to store data key Optional. String type: The specified key name string. value Optional. Object type: The data of any type to be stored.
More examples
Get the data
Retrieve the data named "blah" stored on the element.
jQuery Miscellaneous Methods