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:

1

2

jQuery.data( document.body, "foo", 52 );

jQuery.data( document.body, "bar", "test" );

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.

undefined is not recognized as a data value. Calls such as jQuery.data( el, "name", undefined ) will return the corresponding data for "name", and is therefore the same as jQuery.data( el, "name" ).

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:

1

2

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.