jQuery .data() — Complete Guide to Attaching and Retrieving Element Data
In this tutorial, you will learn about jquery .data(). We cover key concepts, practical examples, and best practices to help you master this topic.
jQuery .data() method attaches arbitrary JavaScript data to DOM elements, providing a clean way to store state, cache values, and associate complex objects with elements without modifying HTML attributes.
What You'll Learn
- Storing and retrieving data with .data()
- Difference between .data() and .attr('data-*')
- Using HTML5 data-* attributes with .data()
- Removing data with .removeData()
- Data storage for complex objects
Why It Matters
DOM elements often need associated data — user IDs, timestamps, references to related elements, or cached API responses. Using .data() keeps this information attached to the element without polluting the HTML or using global variables.
Real-World Use
A drag-and-drop calendar where each event element stores its start time, end time, and event ID via .data(). When dropped on a new time slot, the data is read to update the backend without re-Parsing the DOM.
Data Storage Flow
flowchart LR
A[.data('key', value)] --> B[jQuery Cache]
C[HTML data-attribute] --> D[.data('key') reads on first access]
D --> B
B --> E[Return cached value]
style A fill:#e6f3ff,stroke:#4a90d9,stroke-width:2px
Storing and Retrieving Data
// Store data on an element
$('.card').data('id', 42);
$('.card').data('category', 'premium');
$('.card').data('price', 29.99);
// Retrieve data
var id = $('.card').data('id');
console.log(id); // Output: 42
// Retrieve all data as an object
var allData = $('.card').data();
console.log(allData);
// Output: { id: 42, category: 'premium', price: 29.99 }
Expected output: Data is stored in jQuery's internal cache, keyed by the DOM element. Retrieval returns the stored value. Complex objects (arrays, objects, functions) can be stored and retrieved.
Storing Complex Objects
// Store objects and arrays
$('.product-card').data('details', {
name: 'Laptop',
specs: { cpu: 'i7', ram: '16GB', storage: '512GB' },
inStock: true,
tags: ['electronics', 'sale']
});
// Store functions (not common but possible)
$('.btn').data('onClick', function() {
alert('Custom handler');
});
// Retrieve and use
var details = $('.product-card').data('details');
console.log(details.name); // Output: Laptop
console.log(details.specs.cpu); // Output: i7
console.log(details.tags[0]); // Output: electronics
HTML5 data-* Attributes
jQuery .data() automatically reads HTML5 data-* attributes:
<div id="user-card"
data-user-id="42"
data-user-name="Alice"
data-user-role="admin"
data-preferences='{"theme":"dark","notifications":true}'>
</div>
// These are automatically available via .data()
var card = $('#user-card');
console.log(card.data('userId')); // Output: 42 (number, not string)
console.log(card.data('userName')); // Output: Alice (string)
console.log(card.data('userRole')); // Output: admin (string)
console.log(card.data('preferences')); // Output: { theme: 'dark', notifications: true } (object)
Expected output: jQuery automatically converts data-* attribute names to camelCase and parses JSON, numbers, and booleans. data-user-id becomes data('userId') as a number.
.data() vs .attr('data-*')
// Setting
$('.card').attr('data-id', 42); // Sets HTML attribute
$('.card').data('id', 42); // Sets jQuery cache (does NOT update HTML)
// Reading after setting with .data()
$('.card').attr('data-id', 99);
console.log($('.card').data('id')); // Output: 42 (cached, not re-read)
// Force re-read from DOM (if not previously cached)
$('.card').attr('data-new', 'value');
console.log($('.card').data('new')); // Output: value (first read from DOM)
// Key difference:
// .data() caches on first read from HTML
// Subsequent .data() writes do NOT update the HTML attribute
// .attr() always reads/writes the HTML attribute
.removeData()
// Remove specific data key
$('.card').removeData('id');
// Remove all data
$('.card').removeData();
// Note: .removeData() removes from jQuery cache only
// HTML data-* attributes remain and can be re-read
$('.card').removeData('userId');
console.log($('.card').data('userId')); // Re-read from HTML attribute
Using Data for Event Delegation
// Set data on dynamic elements
$('.item').each(function(index) {
$(this).data('index', index);
});
// Event delegation using data
$('.list').on('click', '.item', function() {
var index = $(this).data('index');
var id = $(this).data('id');
console.log('Clicked item #' + index + ' with ID: ' + id);
});
Data for State Management
// Accordion state
$('.accordion-header').click(function() {
var $body = $(this).next('.accordion-body');
var isOpen = $body.data('open') || false;
// Toggle
$body.data('open', !isOpen);
$body.slideToggle();
});
// Tab state persistence
$('.tab').click(function() {
var tabId = $(this).data('tab');
$('.tab').data('active', false);
$(this).data('active', true);
// Show corresponding panel
});
Performance: Caching with .data()
// BAD: Repeated jQuery lookups
$('.items .title').each(function() {
var text = $(this).text();
var parent = $(this).parent();
// ...
});
// GOOD: Cache jQuery objects using .data()
$('.item').each(function() {
var $item = $(this);
var $title = $item.find('.title');
var $desc = $item.find('.description');
// Store cached jQuery objects
$item.data({
'$title': $title,
'$desc': $desc,
'id': $title.data('id')
});
});
Common Mistakes
Assuming .data() updates HTML attributes -
.data('key', val)stores in jQuery's cache only. The HTML attribute is NOT updated. Use.attr('data-key', val)if you need the HTML to reflect the change.CamelCase confusion with data attributes -
data-user-namein HTML becomesdata('userName')in jQuery.data('username')would not find it.Not clearing data when removing elements - When you
.remove()an element, its data is also removed. But.detach()preserves data. Use.empty()with caution as it may not clean up child element data.Data type parsing surprises -
data-count="0"becomes number 0 (falsy),data-count=""becomes empty string (also falsy), butdata-count="false"becomes boolean false. Test edge cases.Overwriting data with undefined - Setting
.data('key', undefined)does NOT remove the key; it sets the value to undefined. Use.removeData('key')to actually delete the key.
Practice Questions
- How does .data() differ from .attr() when storing values?
- How does jQuery convert HTML data-* attribute names to JavaScript keys?
- What types of values can .data() store?
- How do you remove a single data item from an element?
- What happens when you call .remove() on an element with associated data?
Challenge: Build a sortable list where each list item stores its original index, category, and priority via .data(). Implement drag-to-reorder and log each item's stored data when clicked.
FAQ
Mini Project
Build a product comparison widget where each product card stores name, price, rating, and specs via .data(). Users can select products to compare, and the comparison table reads the stored data to display side-by-side details.
What's Next
Data is often related to positioning. Learn how dimensions and offset methods measure element size and position on the page.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro