This rule raises an issue when getAttribute(), setAttribute(), removeAttribute(), or
hasAttribute() are used with data attributes (attributes starting with data-).
The .dataset property provides a cleaner, more semantic way to work with HTML data attributes compared to generic attribute
methods.
Data attributes are a special category of HTML attributes designed to store custom data. The browser provides the .dataset API
specifically for this purpose, which offers several advantages:
element.dataset.userName is more readable than
element.getAttribute('data-user-name') data-user-name) and
camelCase JavaScript properties (userName) .dataset clearly indicates you’re working with data attributes, making the code’s
intent more obvious .dataset properties are always strings, avoiding potential confusion with other attribute types
Using generic attribute methods for data attributes misses these benefits and can make code less maintainable.
Using generic attribute methods instead of .dataset reduces code readability and maintainability. While functionally equivalent, it
makes the code less expressive about working with data attributes and requires manual handling of name conversions between kebab-case and
camelCase.
Replace getAttribute() calls for data attributes with .dataset property access. The attribute name is automatically
converted from kebab-case to camelCase.
const value = element.getAttribute('data-user-name'); // Noncompliant
const value = element.dataset.userName;
// or with destructuring
const {userName} = element.dataset;