The data() Method

Store and read custom data attached to elements.

Syntax$(el).data("key"); $(el).data("key", value);

.data() reads HTML5 data-* attributes and stores arbitrary values on elements — without touching the visible DOM.

// HTML: <div id="box" data-user-id="42">
$("#box").data("userId");    // 42
$("#box").data("role", "admin"); // set in memory

Note that data-user-id is read as userId (camelCase).

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A shopping cart stores the product ID and price as data on each cart row element with .data() for later totalling.
  • A drag-and-drop board attaches the task status to each card with .data('status', value) without polluting the DOM with data attributes.
  • A tooltip component reads the message from .data('tooltip') set earlier rather than parsing a raw attribute string each time.

More examples

Store and retrieve data on an element

.data() reads both programmatically set values and existing data-* HTML attributes, converting kebab-case to camelCase.

Example · html
<div id="card" data-product-id="42" data-price="9.99">Widget</div>
<button id="read">Read data</button>
<p id="out"></p>
<script>
$(function () {
  $("#read").click(function () {
    var id    = $("#card").data("productId");
    var price = $("#card").data("price");
    $("#out").text("ID: " + id + "  Price: $" + price);
  });
});
</script>

Set data programmatically at runtime

.data("done", true) stores an arbitrary value on the element in jQuery's internal cache without touching the HTML.

Example · html
<ul id="tasks">
  <li>Task A</li>
  <li>Task B</li>
</ul>
<button id="markDone">Mark first done</button>
<p id="status"></p>
<script>
$(function () {
  $("#markDone").click(function () {
    var $first = $("#tasks li").first();
    $first.data("done", true).css("text-decoration", "line-through");
    $("#status").text("Done: " + $first.data("done"));
  });
});
</script>

Pass complex objects via .data()

.data() can store any JavaScript value including nested objects, acting as a lightweight element-scoped store.

Example · html
<button id="storeUser">Store user</button>
<button id="readUser">Read user</button>
<p id="info"></p>
<script>
$(function () {
  $("#storeUser").click(function () {
    $("body").data("currentUser", { id: 7, name: "Alice", role: "admin" });
  });
  $("#readUser").click(function () {
    var u = $("body").data("currentUser");
    if (u) $("#info").text(u.name + " (" + u.role + ")");
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.