jQuery .data() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Element data

What You’ll Learn

.data() attaches arbitrary JavaScript values to elements and reads them back — including values seeded from HTML5 data-* attributes. This tutorial covers setters and getters, object merges, data-* conversion, camelCase keys, comparisons with .attr() and jQuery.data(), five examples, and try-it labs.

01

Set

Key / value

02

Get

By key

03

All keys

.data()

04

data-*

HTML5 seed

05

vs .attr()

Cache vs DOM

06

Since 1.2.3

Core API

Introduction

This page covers the collection method .data() (same API as api.jquery.com/data). The low-level static jQuery.data() utility is documented under Utilities.

Plugins and UI widgets often need to remember state on a DOM node — options, counters, objects — without inventing fragile global variables. Since jQuery 1.2.3, .data() is the standard way to do that.

Values live in jQuery’s internal cache (not as expando properties you manage yourself), which helps avoid circular-reference memory leaks. You can store numbers, strings, objects, arrays, and more — anything except undefined.

Since 1.4.3, HTML5 data-* attributes also seed that cache the first time you call .data(). Pair this topic with .removeData(), jQuery.hasData(), and the DOM hub.

Understanding the .data() Method

Think of each element as having a small private dictionary. Writing $(el).data("foo", 52) puts 52 under key foo. Reading $(el).data("foo") returns it. Calling .data() with no arguments returns the whole dictionary for the first matched element.

Setting with an object (since 1.4.3) shallow-merges keys into the existing store — it no longer replaces the entire object like early 1.4 versions did.

💡
Beginner Tip

.data() does not change HTML attributes. Use .attr("data-foo", "bar") when you need the markup itself updated. Use .data() for runtime state and typed values.

📝 Syntax

Common signatures:

jQuery
.data( key, value )     // set one key (1.2.3+)
.data( obj )            // merge keys from an object (1.4.3+)
.data( key )            // get one key (1.2.3+)
.data()                 // get all data as an object (1.4+)

Parameters

  • key (String) — name of the data entry.
  • value (Anything except undefined) — value to store.
  • obj (Object) — key/value pairs to merge into the cache.

Return value

  • Setter — the jQuery collection (chainable).
  • Getter with key — the stored value (or undefined).
  • Getter with no args — a plain object of all keys for the first element.

Quick set / get (official style)

jQuery
$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { isManual: true } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
$( "body" ).data( "foo" ); // 52
$( "body" ).data();        // { foo: 52, bar: {…}, baz: […] }

⚡ Quick Reference

GoalCode
Store a value$( el ).data( "count", 3 )
Read a value$( el ).data( "count" )
Merge several keys$( el ).data( { a: 1, b: 2 } )
Read everything$( el ).data()
Read data-* as string$( el ).attr( "data-role" )
Delete a key$( el ).removeData( "count" )
Storage
cache

Internal jQuery data store

HTML seed
data-*

Read once into the cache

Keys
camel

Dashes → camelCase (jQuery 3)

Cleanup
.removeData()

Clear cached keys

📋 .data() vs .attr() vs jQuery.data()

.data().attr("data-…")jQuery.data(el, …)
Where it livesjQuery cacheDOM attributeSame cache (static)
TypesAny JS type*Strings in markupAny JS type*
Best forRuntime / plugin stateMarkup & raw stringsRaw DOM helpers

*Except undefined as a stored value.

Examples Gallery

Examples follow the official jQuery API demos and everyday patterns. Use View Output or Try It Yourself to explore each case.

📚 Getting Started

Store values and read them back — the core workflow.

Example 1 — Store an Object, Read Properties

Official demo: attach a small object, then show its fields.

jQuery
$( "div" ).data( "test", { first: 16, last: "pizza!" } );
$( "span" ).first().text( $( "div" ).data( "test" ).first );
$( "span" ).last().text( $( "div" ).data( "test" ).last );
Try It Yourself

How It Works

One key can hold a whole object. Reading .data("test") returns that object so you can use .first / .last like normal JavaScript.

Example 2 — Get, Set, and Remove a Named Key

Official interactive pattern with .data and .removeData.

jQuery
$( "button" ).on( "click", function() {
  var value;
  switch ( $( "button" ).index( this ) ) {
    case 0:
      value = $( "div" ).data( "blah" );
      break;
    case 1:
      $( "div" ).data( "blah", "hello" );
      value = "Stored!";
      break;
    case 2:
      $( "div" ).data( "blah", 86 );
      value = "Stored!";
      break;
    case 3:
      $( "div" ).removeData( "blah" );
      value = "Removed!";
      break;
  }
  $( "span" ).text( "" + value );
});
Try It Yourself

How It Works

Same key can hold different types over time. .removeData("blah") clears only that entry from the cache.

📈 Practical Patterns

HTML5 attributes, merging objects, and choosing attr vs data.

Example 3 — Read HTML5 data-* Attributes

jQuery converts numbers, booleans, and JSON-looking strings on first read.

jQuery
<div id="page"
  data-role="page"
  data-last-value="43"
  data-hidden="true"
  data-options='{"name":"John"}'></div>
$( "#page" ).data( "role" );       // "page"
$( "#page" ).data( "lastValue" );  // 43
$( "#page" ).data( "hidden" );     // true
$( "#page" ).data( "options" ).name; // "John"
Try It Yourself

How It Works

data-last-value becomes the key lastValue. For an unconverted string, use .attr("data-last-value") instead.

Example 4 — Merge Keys With an Object

Pass an object to update several entries without wiping others (1.4.3+).

jQuery
$( "#box" )
  .data( "foo", 52 )
  .data( { bar: true, baz: [ 1, 2, 3 ] } );

console.log( $( "#box" ).data() );
// { foo: 52, bar: true, baz: [1, 2, 3] }
Try It Yourself

How It Works

Object form is ideal for plugin option bags. Existing keys not mentioned in the object remain untouched.

Example 5 — .data() vs .attr()

Updating data does not rewrite the attribute in the DOM.

jQuery
// Markup: <div id="x" data-score="10"></div>
$( "#x" ).data( "score" );          // 10 (number from attribute)
$( "#x" ).data( "score", 99 );      // cache now 99
$( "#x" ).attr( "data-score" );     // still "10" in the DOM

$( "#x" ).attr( "data-score", "50" ); // updates attribute string
// cache may still be 99 until you removeData / re-read carefully
Try It Yourself

How It Works

Attributes are initialized into the cache once. After that, treat .data() as the runtime source of truth, or clear with .removeData() if you need to re-seed from attributes.

🚀 Common Use Cases

  • Plugin / widget state — options, timers, and flags on the host element.
  • Counters and IDs — remember which row or tab is active.
  • Config from markup — read data-* into typed values on init.
  • Caching computed results — avoid re-querying expensive setup.
  • Cleanup with removeData — reset before re-init or destroy.
  • Guards with hasData — check whether a cache already exists.

🧠 How .data() Fits

1

Optional HTML seed

data-* attributes may exist in markup.

Markup
2

First .data() call

Attributes are parsed into the internal cache once.

Seed
3

Get / set / merge

Further calls read and write the cache only.

Runtime
4

Clean up when done

Use .removeData() or element removal to clear.

📝 Notes

  • Setters since 1.2.3; object setter 1.4.3; no-arg getter 1.4.
  • Do not use .data() on <object> (unless Flash), <embed>, or <applet>.
  • XML documents: attaching data is not reliably cross-platform (legacy IE note in the docs).
  • undefined is not a valid stored value.
  • Updating .data() does not update DOM attributes.
  • jQuery 3 camelCases dashed keys like the HTML dataset API.
  • Getters that take a key operate on the first element in the collection.
  • Related: .removeData(), jQuery.hasData(), jQuery.data().

Browser Support

.data() has been part of jQuery since 1.2.3+ (with later signature expansions). It works in every browser supported by your jQuery build — including modern evergreen browsers with jQuery 3.x. The cache is implemented by jQuery.

jQuery 1.2.3+

.data()

Stable element data API across supported jQuery versions. Prefer .data() on collections over the static utility.

100% With jQuery 1.2.3+
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
.data() 1.2.3+

Bottom line: Use for runtime state and typed data-* reads; use .attr() when you need the attribute string.

Conclusion

.data() is jQuery’s friendly API for attaching typed values to elements and reading HTML5 data-* into that same store. Keep attributes and cache separate in your mental model, and clean up with .removeData() when widgets tear down.

Next up: .removeData() to delete cached keys.

💡 Best Practices

✅ Do

  • Use .data() for plugin and widget runtime state
  • Read data-* through .data() when you want typed values
  • Call .removeData() on destroy / reset
  • Prefer camelCase keys that match jQuery 3 rules
  • Document which keys your plugin owns

❌ Don’t

  • Expect .data() writes to update HTML attributes
  • Store undefined as a value
  • Put data on object / embed / applet
  • Mix attr and data as competing sources for the same key
  • Forget that getters use only the first matched element

Key Takeaways

Knowledge Unlocked

Five things to remember about .data()

Store and read element-associated values safely.

5
Core concepts
{} 02

Merge

Object

1.4.3+
* 03

data-*

Seeds

HTML5
04

Not

.attr()

Cache
05

Clear

.removeData()

Cleanup

❓ Frequently Asked Questions

.data() stores or reads arbitrary JavaScript values associated with matched elements in jQuery’s internal cache (safe from common memory-leak patterns). You can set a key/value, set many keys from an object, read one key, or read the whole data object. Available since jQuery 1.2.3 (object setter and no-arg getter later).
data-* attributes live in the DOM markup. The first time you call .data() on an element, jQuery reads those attributes into its cache (with type conversion). After that, .data() uses the cache — changing .data() does not update the attribute. To change the attribute itself, use .attr("data-key", value).
.data() is the collection method: $("#el").data("key", value). jQuery.data(element, key, value) is the static utility that takes a raw DOM node. Both talk to the same cache; prefer .data() in everyday code. See the Utilities jQuery.data() tutorial for the static form.
Since jQuery 1.4, .data() with no arguments returns a plain object of all stored keys for the first matched element. Missing keys when reading a name return undefined. An element with no data yet yields {}.
No. undefined is not treated as a data value. Calling .data("name", undefined) does not store undefined — it returns the jQuery object for chaining (setter signature behavior). Use null or omit the key instead.
Since jQuery 3 (aligned with the HTML dataset API), a dash followed by a lowercase letter becomes camelCase. So data-last-value maps to .data("lastValue"). Writing .data({ "my-name": "aValue" }) and then .data() returns { myName: "aValue" }.
Did you know?

jQuery tries hard when converting data-* strings: "100" becomes the number 100, but strings like "1E02" or "100.000" stay strings because converting them would change how they look when turned back into text.

Next: .removeData() Method

Clear keys from jQuery’s internal data cache on matched elements.

.removeData() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful