jQuery: data() method

The jQuery's data() method (and its counterpart removeData()) allows you to attach any kind of data to a jQuery element. This method works by creating a referenced object literal that will be accessible within an element's context. In this way, you can store arbitrary data avoiding memory leaks, which is great from a performance perspective. This method has the following syntax:

$.data(element, name, data);

where element is a reference to a jQuery element, name is a reference name given to our data object and data is an object literal containing our data. For example, if we have an element such as this:

<div id="foo"></div>

and we want to insert some data within it, here's how we can do:

var element = $('#foo');

$.data(element, 'test', {content: 'Hello World'});

element.text($.data(element, 'test').content);

Now our element will contain the string 'Hello World', thanks to this statement:

element.text($.data(element, 'test').content);

content is the property of the object literal defined with the data() method and here we're only accessing this property specified earlier. Everything works exactly in the same way as normal access to JavaScript object members, nothing more.

When you're done with your object data, you'll probably need to free memory. You can use the removeData() method:

$.removeData(element, 'test');

This method accepts as its parameters the jQuery element which has some data attached to it and the reference name we've chosen earlier. Once called this method, all data are deleted and trying to access it returns undefined.

Here's a more practical example:

<div id="test">
  <strong>Window width:</strong>
$(document).ready(function() {

  var test = $('#test');
  $.data(test, 'window', {size: $(window).width()});
  $('#add').click(function(e) {
    test.find('span').text($.data(test, 'window').size);
  $('#remove').click(function(e) {
    $.removeData(test, 'window');
    test.find('span').text(typeof $.data(test, 'window'));


You can see this demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.