.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 |
|
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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|