.data( key, value )Returns: jQuery
Description: Store arbitrary data associated with the matched elements.
-
version added: 1.2.3.data( key, value )
-
version added: 1.4.3.data( obj )
-
objType: ObjectAn 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:
|
1
2
3
4
5
|
|
Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr.
Prior to jQuery 1.4.3, .data( obj ) completely replaced all data. Since jQuery 1.4.3, data is instead extended by shallow merge.
Since jQuery 3, every two-character sequence of "-" (U+002D) followed by a lowercase ASCII letter in a key is replaced by the uppercase version of the letter, in alignment with the HTML dataset API. A statement like $( "body" ).data( { "my-name": "aValue" } ).data(); will return { myName: "aValue" }.
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.
-
undefinedis not recognized as a data value. Calls such as.data( "name", undefined )will return the jQuery object that it was called on, allowing for chaining.
Example:
Store then retrieve a value from the div element.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
|