To read a data-id attribute in vanilla JavaScript, access element.dataset.id (or element.getAttribute("data-id")). In jQuery, use $(element).data("id") (or $(element).attr("data-id") when you want the raw string attribute without jQuery’s automatic type conversion or internal .data() cache).
1. Reading data-id in Vanilla JavaScript
In the DOM dataset API, kebab-case data-* names map to camelCase keys (data-id -> dataset.id, data-user-id -> dataset.userId), always returning a string or undefined if missing.
// Vanilla JS: dataset.id vs getAttribute("data-id")
function getElementId(el) {
if (!el) return null;
// dataset.id returns string or undefined; getAttribute returns string or null
return el.dataset.id ?? el.getAttribute("data-id");
}
// Event delegation on a list of items
document.addEventListener("click", (event) => {
const item = event.target.closest("[data-id]");
if (!item) return;
const rawId = item.dataset.id;
const numericId = Number(rawId);
console.log("Clicked item:", { rawId, numericId });
});
el.dataset.id: Clean, idiomatic DOM access fordata-id; returnsundefinedif the attribute is not present.el.getAttribute("data-id"): Reads the raw HTML attribute string directly (returnsnullif absent), which is handy when you want strictnullchecks or want to avoiddatasetproperty quirks.
2. Reading data-id in jQuery (.data("id") vs. .attr("data-id"))
jQuery provides both .data("id") and .attr("data-id"), and knowing the difference prevents subtle bugs with numeric IDs or later updates.
// jQuery: .data("id") vs .attr("data-id")
$("#itemsList").on("click", "[data-id]", function () {
const $el = $(this);
// .data("id") auto-parses numeric strings like "42" into Number 42
const parsedId = $el.data("id");
// .attr("data-id") always returns the raw attribute string (e.g., "42") or undefined
const attrId = $el.attr("data-id");
console.log({ parsedId, typeOfParsed: typeof parsedId, attrId, typeOfAttr: typeof attrId });
});
- When to use
.data("id"): Convenient when you want jQuery’sdata-*parsing or store extra runtime metadata in jQuery’s internal cache. - When to use
.attr("data-id"): Better when you want the exact string from the DOM attribute—especially if IDs have leading zeros ("007"), look like numbers ("1234567890123456789") that could lose precision as JS floats, or are updated viasetAttribute/.attr().
3. Common Traps to Avoid
- Assuming
dataset.idor.attr("data-id")returns aNumber: HTML attributes are strings—convert explicitly withNumber(id)orparseInt(id, 10)when doing numeric comparisons or math. - Mutating
.data("id", newVal)expecting the HTMLdata-idattribute to update: jQuery’s.data()updates an internal cache rather than rewriting the DOM attribute; use.attr("data-id", newVal)orel.dataset.id = newValif the DOM attribute itself must change. - Forgetting event delegation on dynamic elements: If items are rendered dynamically via JavaScript or AJAX, bind listeners to a static parent container using
.closest("[data-id]")or.on("click", "[data-id]", ...).
TL;DR: Use el.dataset.id in vanilla JavaScript, and use $(el).attr("data-id") in jQuery for the raw attribute string (or $(el).data("id") when you want jQuery’s parsed data value).
Are you reading data-id inside a delegated click/change handler on dynamic items, or do you need to update/convert the ID value after reading it?
