← Back to Chapters

jQuery .data() Method

? jQuery .data() Method

? Quick Overview

The .data() method in jQuery allows you to store, retrieve, and manage custom data associated with DOM elements without modifying the HTML markup.

? Key Concepts

  • Stores data internally in jQuery’s cache
  • Works with data-* HTML attributes
  • Avoids repeated DOM manipulation
  • Data is automatically type-casted

? Syntax / Theory

The .data() method can be used to both set and get values.

  • $(selector).data(key) → Get value
  • $(selector).data(key, value) → Set value

? Code Examples

? View Code Example
// Storing and retrieving data using jQuery .data()
$("#box").data("count", 10);
let value = $("#box").data("count");
console.log(value);
? View Code Example
// Reading HTML5 data-* attribute using .data()
let role = $("#user").data("role");
console.log(role);

? Live Output / Explanation

Explanation

The first example stores a number inside the selected element without changing HTML. The second example reads a value directly from a data-role attribute.

? Interactive Example

Interactive State Manager

Current Status: Inactive

Total Clicks: 0

? View Code Example
// Button click increases value stored using .data()
let btn = $("#btn");
btn.data("clicks", 0);

btn.on("click", function () {
let count = btn.data("clicks");
btn.data("clicks", count + 1);
alert("Clicks: " + btn.data("clicks"));
});

? Use Cases

  • Storing temporary UI state
  • Caching values for performance
  • Tracking user interactions
  • Passing data between handlers

? Tips & Best Practices

  • Use .data() instead of global variables
  • Prefer camelCase keys for consistency
  • Do not rely on data-* attributes changing dynamically
  • Clear data using .removeData() when needed

? Try It Yourself

  • Create a counter using .data()
  • Store user-selected theme preference
  • Compare .data() vs .attr()
  • Use .removeData() and observe behavior