Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 56 ยท Manipulating the DOM

Storing Data with .data()

Use jQuery .data() to attach values to elements and read data-* attributes: camelCase keys, automatic type conversion, the internal cache and .removeData().

Interfaces constantly need to remember small facts about elements: which product a button belongs to, how many times a card was opened, the original height of a panel before it collapsed. You could hide those facts in class names or invented attributes, but jQuery offers a cleaner place: the .data() method. It attaches values to elements, reads HTML data-* attributes, and keeps both in one tidy interface.

There is one detail that surprises almost everyone: .data() is not a window onto the attribute. It reads the attribute once, converts it, and then keeps its own copy. Understanding that copy explains every odd behavior of the method.

Where the value lives

data-* attribute Text in the HTML. Read once, on first access.
jQuery cache A private store per element. This is what .data() uses.

After the first read, changing the attribute does not change .data().

1 / 2

Reading data-* attributes

Given this markup:

HTML
<button id="buy" data-product-id="42" data-in-stock="true" data-tags='["new","sale"]'>Buy</button>

you read the values by name, without the data- prefix and in camelCase:

JavaScript
$("#buy").data("productId");   // 42       (a number)
$("#buy").data("inStock");     // true     (a boolean)
$("#buy").data("tags");        // ["new", "sale"]  (a real array)

The attribute name data-product-id turns into the key productId, the same way dataset works in plain JavaScript. jQuery also accepts the dashed form, .data("product-id"), but camelCase is the convention and avoids confusion.

Type conversion rules

When jQuery reads an attribute for the first time, it tries to give you a useful type:

  • "true" and "false" become booleans, and "null" becomes null.
  • A string that looks like a plain number and round-trips exactly becomes a number. "42" becomes 42, but "007" and "1e3" stay strings, because converting them would lose information.
  • A string that starts with { or [ is parsed as JSON. Invalid JSON is left as a string. Remember that JSON needs double quotes inside, which is why the attribute above is wrapped in single quotes.
  • Anything else stays a string.

If you need the raw text instead, use .attr("data-product-id"), which always returns a string.

Reading data attributes and their types

Writing data

Pass a second argument to store a value. You can store anything: numbers, arrays, objects, functions, even references to other elements.

JavaScript
$("#buy").data("clicks", 0);
$("#buy").data({ owner: "Ana", level: 3 });   // several at once
var all = $("#buy").data();                    // an object with every key

Calling .data() with no arguments returns an object holding all the stored values plus any data-* attributes (converted and in camelCase). Treat that object as read-only; to change a value, call .data(key, value).

Two important facts follow from the cache design:

  1. Writing does not touch the HTML. After .data("clicks", 5), the DOM inspector will not show data-clicks. Nothing is visible in the markup, and nothing is lost when someone copies the element's outerHTML.
  2. Reading is cached. After the first .data("price"), jQuery stops looking at the attribute. If other code then runs .attr("data-price", 99), .data("price") still returns the old value.

That second point is the most common source of "my data is stale" bugs. Choose a single source of truth. If the value belongs in the markup (for example, CSS selectors depend on it), read and write it with .attr(). If it is internal state, use .data() for both.

The cache is separate from the attribute

Removing data

.removeData("key") deletes one stored value; .removeData() with no arguments deletes everything stored through jQuery for those elements. It does not remove the data-* attribute from the HTML. As the demo shows, once the cached value is gone, the next .data("count") reads the attribute again.

You can also remove several keys at once: .removeData(["a", "b"]) or .removeData("a b").

Storing objects without leaks

A classic memory problem with browsers is attaching JavaScript objects to DOM nodes in a way that keeps both alive forever. jQuery avoids most of it for you: its store is keyed to the element, and when you remove an element with jQuery's own methods (.remove(), .empty(), .html()), jQuery also clears the stored data and event handlers. Keep these habits:

  • Remove elements with jQuery methods, not with native parent.removeChild(node), if they carry data. See Removing, Replacing, Wrapping for the details.
  • Do not store a reference from an element to a large object that itself points back to the element unless you plan to clean it up.
  • Store small, plain values where you can: IDs, counters, flags, option objects.

This is the same per-element state technique that writing plugins relies on: a plugin stores its instance on the element so a second call finds it.

The low-level jQuery.data()

There is also a utility form, jQuery.data(element, key, value), which takes a raw DOM element instead of a jQuery collection. It reads and writes the same private store but does not read data-* attributes or convert types. It is faster, and plugin authors sometimes use it, but for everyday code .data() is clearer.

JavaScript
var el = document.getElementById("buy");
jQuery.data(el, "clicks", 3);
jQuery.data(el, "clicks");   // 3

Checking for stored data with jQuery.hasData()

jQuery.hasData(element) answers one question: does this raw DOM element have anything in jQuery's private store? That store holds .data() values and also the bookkeeping for handlers attached with .on(). It returns a boolean, so you can skip cleanup work on elements that never had state.

JavaScript
var el = document.getElementById("buy");
jQuery.hasData(el);              // false
$(el).data("clicks", 3);
jQuery.hasData(el);              // true
$(el).removeData("clicks");
jQuery.hasData(el);              // false again, if nothing else was stored

Pass the raw element, not a jQuery collection: use jQuery.hasData($("#buy")[0]).

data() versus dataset

Modern JavaScript has element.dataset.productId, which always returns strings and always reads the live attribute. Use dataset when you want exactly the markup; use jQuery's .data() when you want converted types or hidden state. Mixing both on the same key is where the stale-value trap appears.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given <div data-max-width="300">, how do you read the value as a number with jQuery?

    Drop the data- prefix and use camelCase. .data() also converts the text "300" to the number 300.
  2. 2. You run $("#x").data("count", 5). What happens to the HTML?

    Writing with .data() never touches the markup. Use .attr("data-count", 5) if the attribute itself must change.
  3. 3. A data attribute is read with .data("price"). Later code sets the attribute with .attr("data-price", 99). What does .data("price") return now?

    jQuery reads the attribute once and then serves its cached copy. Pick one source of truth to avoid this staleness.
  4. 4. What does .data("zip") return for data-zip="007"?

    jQuery only converts strings that round-trip exactly to a number. "007" would become 7 and lose its zeros, so it stays a string.

Summary

  • .data(key) reads a data-* attribute using the camelCase name without the data- prefix.
  • Values are converted: numbers, booleans, null, and JSON arrays or objects; strings that would lose information stay strings.
  • .data(key, value) stores any value in jQuery's private store and never changes the HTML.
  • The attribute is read once; after that the cache wins, so use one source of truth.
  • .removeData() clears stored values only; the next read may fall back to the attribute.
  • jQuery.data(el, ...) is the low-level, faster form that takes a raw DOM element.
  • Remove elements with jQuery methods so their stored data and handlers are cleaned up.

Next, learn how to put new elements on the page in Inserting Content.