SyntaxStudy
Sign Up
jQuery Advanced 6 min read

jQuery DOM Data Storage

Storing arbitrary data on DOM elements without cluttering the HTML with custom attributes is a clean pattern enabled by jQuery's .data() method. It uses an internal cache keyed by each element, so the data lives in JavaScript memory and is automatically cleaned up when the element is removed via jQuery methods.

Setting Data

.data(key, value) stores a value under the given key for each matched element. The value can be any JavaScript type — strings, numbers, objects, arrays, even functions. Subsequent calls overwrite the previous value.

Reading Data

.data(key) retrieves the value. On first access, jQuery also reads any matching data-* HTML attribute, converting it to the appropriate JavaScript type (numbers, booleans, JSON objects are auto-parsed).

Removing Data

.removeData(key) deletes a specific key, or deletes all stored data when called with no arguments.

  • Store objects: $('#el').data('config', { page: 1, size: 10 })
  • Read back: $('#el').data('config').page
  • Auto-parse HTML attr: data-count="5" returns the number 5
Example
// Store data on a button
$('#load-more').data('page', 1);

// Increment on each click
$('#load-more').on('click', function () {
    var page = $(this).data('page');
    loadItems(page);
    $(this).data('page', page + 1);
});

// Store an object
$('#chart').data('options', {
    type   : 'bar',
    animate: true
});
var opts = $('#chart').data('options');
console.log(opts.type); // "bar"

// Auto-parse from HTML attribute
// <div id="el" data-score="42"></div>
var score = $('#el').data('score'); // number 42

// Remove all stored data
$('#el').removeData();
Pro Tip

jQuery .data() auto-parses data-* HTML attributes to their correct JS types on first read.