unicorn/prefer-dom-node-dataset
Require .dataset instead of the attribute methods for data-* attributes
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:
[lint.rules]
"unicorn/prefer-dom-node-dataset" = "error" # or "warn"Examples#
element.setAttributePrefer using dataset over setAttribute.("data-user-id", user.id);
const id = element.getAttributePrefer using dataset over getAttribute.("data-user-id");
if (element.hasAttributePrefer using dataset over hasAttribute.("data-user-id")) {
element.removeAttribute("data-user-id"Prefer using dataset over removeAttribute.);
}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:
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.