# 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.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

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

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 4} */}
```js
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");
}
```

Not reported:

{/* good */}
```js
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:

{/* good */}
```js
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.
