Like many others, I believe that you should avoid adding useless data attributes to your markup purely for the purposes of testing (or targeting for other purposes like CSS selectors). I avoid like the plague littering my components with random and haphazard data attributes. I believe that for the purposes of both styling and testing, you can almost always get by with this order of preference:
- Select based on the tag name itself
- Select based on some other semantic attributes of the markup
- Select based on ARIA attributes that you would have had to use anyway
- Then if all else fails, fall back to a limited set of extra data attributes
So with this in mind, I strongly limit the amount of data attributes in the codebase and I follow a strict system for how I use them:
data-component="name"
is used on a component's root element, when necessary, to identify the component in the DOM.
data-part="name"
is used inside a component to identify its parts when there is no better semantic way to do so.
Serialized Phoenix commands: for instance, commands encoded as described here. These attributes serve a necessary purpose and are used freely where needed.
Data required by JavaScript: technically, this is the same as the previous category. Attributes that pass necessary data to the frontend are used as needed.
There are a couple of other outliers, such as data-theme
on the body to store the light or dark theme setting.