unicorn/prefer-dom-node-dataset

Require .dataset instead of the attribute methods for data-* attributes

fixable

Every data-* attribute on an element is also a property of element.dataset, with the name in camel case. For example, data-user-id is dataset.userId. Reading and writing a property is shorter than calling getAttribute(), setAttribute(), hasAttribute() or removeAttribute() with a string.

--fix rewrites the call. setAttribute() and removeAttribute() are only rewritten when the call is a standalone statement.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/prefer-dom-node-dataset" = "error" # or "warn"

Examples#

example.js4 problems
element.setAttribute("data-user-id", user.id);
const id = element.getAttribute("data-user-id");

if (element.hasAttribute("data-user-id")) {
  element.removeAttribute("data-user-id");
}
example.jsNo problems
element.dataset.userId = user.id;
const id = element.dataset.userId;

if (Object.hasOwn(element.dataset, "userId")) {
  delete element.dataset.userId;
}

Other attributes aren't reported. Neither is an awaited getAttribute(), because that's most likely a Playwright locator, not a DOM element:

example.jsNo problems
element.setAttribute("aria-label", label);
const id = await page.locator(".user").getAttribute("data-user-id");

When not to use it#

For a missing attribute, getAttribute() returns null and dataset gives undefined. Check comparisons with null before you apply the fix.