.data() Summary
jQuery's .data() attaches typed data to elements, reads HTML data-* attributes automatically, and cleans up with .remove(). Use it for element-scoped runtime state.
jQuery's .data() attaches typed data to elements, reads HTML data-* attributes automatically, and cleans up with .remove(). Use it for element-scoped runtime state.
// Set
$(el).data("key", value);
$(el).data({ key1: v1, key2: v2 });
// Get
const val = $(el).data("key");
const all = $(el).data(); // all keys as object
// Remove
$(el).removeData("key");
$(el).removeData(); // remove all
// HTML data-* attributes auto-read on first access
// <div data-user-id="5"> → .data("userId") === 5
Prefer .data() over global variables for element-specific state — it scales to many elements naturally.