.data() MethodThe .data() method in jQuery allows you to store, retrieve, and manage custom data associated with DOM elements without modifying the HTML markup.
data-* HTML attributesThe .data() method can be used to both set and get values.
$(selector).data(key) → Get value$(selector).data(key, value) → Set value
// Storing and retrieving data using jQuery .data()
$("#box").data("count", 10);
let value = $("#box").data("count");
console.log(value);
// Reading HTML5 data-* attribute using .data()
let role = $("#user").data("role");
console.log(role);
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.
Current Status: Inactive
Total Clicks: 0
// 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"));
});
.data() instead of global variablesdata-* attributes changing dynamically.removeData() when needed.data().data() vs .attr().removeData() and observe behavior