.data() stores or reads arbitrary values on matched elements in jQuery’s internal cache (since 1.2.3) — safer than inventing expando properties yourself.
Syntax
Start with these common calls. Keep them short and readable.
jQuery
$("#el").data("foo", 52) // set
$("#el").data("foo") // → 52
$("#el").data({ bar: true }) // set many (1.4.3+)
$("#el").data() // → { foo: 52, bar: true }
// HTML5 data-* seeds the cache on first read:
// <div data-role="page" data-last-value="43">
$("#el").data("role") // → "page"
$("#el").data("lastValue") // → 43 (camelCase)
Call
What it does
.data()
Learn jQuery .data(): store and read values on elements, HTML5 data-* attributes, camelCase keys, .data vs .attr, removeData, examples, pitfalls, and FAQs.
Load jQuery before your script (CDN or local file), then wrap DOM work in $(function () { ... }) when needed.
Parameters
Parameter
Description
Step 1
Select the element that should own the data.
Step 2
Set with .data(key, value) or .data({ key: value }).
Step 3
Read with .data(key) or .data() for the whole object.
Return Value
Return Value
Description
jQuery object
Most setters and traversing helpers return the jQuery collection so you can chain more methods.
Value / undefined
Getters usually return a value from the first matched element, or undefined when nothing applies.
Markup.data-* attributes declare initial values in HTML.
First read. jQuery copies them into the cache and converts types.
CamelCase.data-last-value becomes lastValue.
Frequently Asked Questions
.data() stores or reads arbitrary JavaScript values on matched elements in jQuery’s internal cache. You can set a key/value, set many keys from an object, read one key, or read the whole object. Available since jQuery 1.2.3.
data-* attributes live in markup. The first .data() call reads them into the cache (with type conversion). After that, .data() uses the cache — changing .data() does not update the attribute. Use .attr("data-key", value) to change the attribute itself.
$("#el").data(key, value) is the collection method. jQuery.data(element, key, value) is the static utility on a raw DOM node. Both use the same cache; prefer .data() in everyday code.
Since jQuery 1.4, .data() with no arguments returns a plain object of all stored keys for the first matched element. A missing key returns undefined. An element with no data yields {}.
No. .data("name", undefined) does not store undefined — it returns the jQuery object for chaining. Use null or omit the key instead.
Since jQuery 3, a dash plus a lowercase letter becomes camelCase (HTML dataset rules). data-last-value maps to .data("lastValue").
Do not use .data() on object, applet, or embed elements (except some Flash object cases). Browsers and plugins make those unreliable.