brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: element.dataset reads data-* attributes as camelCase properties

Javascript
~/tips/tip-js-dataset-data-attributes

delete item.dataset.status; // removes the attribute

Store small bits of state in the markup and read them without getAttribute.

Data attributes are the simplest way to pass a value from the HTML to a script, like the id of a row. dataset gives you all of them as properties.

<li data-post-id="42" data-status="draft">My post</li>

const item = document.querySelector("li");
item.dataset.postId;          // "42"
item.dataset.status = "live"; // sets data-status="live"
delete item.dataset.status;   // removes the attribute
Number(item.dataset.postId);  // 42

The name after data- turns into camelCase: data-post-id becomes postId. Writing to a property creates or updates the attribute, and delete removes it. The attributes stay visible in the inspector, which makes state easy to follow while you test.

CSS can use them too. li[data-status="draft"] styles drafts, so a script only needs to flip the value and the styling follows.

Everything is a string. A missing attribute reads as undefined, a number comes back as text, and data-active="false" is the string “false”, which is truthy. I’d convert explicitly with Number() or a comparison like === "true".

Keep them for small values. Large JSON in an attribute is slow to parse and awkward to escape, and nothing in a data attribute is hidden: anyone can read and change it, so never use it for anything the server should trust.

Further reading: MDN: HTMLElement.dataset, MDN: Use data attributes

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link