Prefer Dataset
ID |
javascript.prefer_dataset |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
JavaScript |
Tags |
best-practice, dom, simplification |
Description
Reports getAttribute("data-…") and setAttribute("data-…"), where the dataset map addresses the same value without a string key.
const id = row.getAttribute("data-user-id"); // FLAW — row.dataset.userId
row.setAttribute("data-state", "open"); // FLAW — row.dataset.state = "open"
Only a key the rule can read is reported: a plain quoted string whose remainder after data- is a name dataset can actually address. A computed key, and an attribute carrying an upper-case letter — unreachable through dataset, whose mapping is defined only over lower-case names — are left alone.
Rationale
-
The string key is invisible to every tool that renames things. A search for the attribute finds the markup and the CSS but not this call, and a rename leaves the call reading an attribute that no longer exists — returning
nullrather than failing, so the defect surfaces far from its cause. -
dataset.userIdis an ordinary property access. A typo is visible at the point of use, an IDE can follow it, and a bundler or minifier will not silently disagree with the markup. -
The
datasetform also states the intent: these are the element’s own data entries, not arbitrary attributes.