A repository of over 1000 quality jQuery plugins

jQuery .data()

Learn all about the jQuery function .data().

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
$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
$( "body" ).data( "foo" ); // 52
$( "body" ).data(); // { foo: 52, bar: { myType: "test", count: 40 }, baz: [ 1, 2, 3 ] }

In jQuery 1.4.3 setting an element’s data object with .data(obj) extends the data previously stored with that element.

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.