If you've been working in web development for any length of time, you've probably seen or written code that resembles this
Data Attributes: Introduction
Data attributes provide a better approach to choose items. For those of you who are unfamiliar, data attributes are simply custom attributes that you may add to any HTML element. They always begin with data-. For instance, you might have an element with the data-accordion-container property like this:
These custom data properties can also have values specified, like in the case of this div with
As this essay is not about data attributes, I won't go into great detail about them; however, if you're interested, you can read my comprehensive article on data attributes. After defining data attributes, allow me to now explain why you should choose items based on them rather than classes.
The first and most apparent benefit is that your selections can be more expressive. It is possible to create simple dynamic selectors by using the value of a data property in the selection. Imagine, for illustration, that when clicked, an element may switch between being active and being inactive. If we used a class-based methodology, we would require classes for active and inactive states, which would result in the following elements:
<div class="active">...</div> <div class="inactive">...</div>
<div>...</div> <div class="inactive">...</div>
The issue with this strategy is that since there is no class designating the element as active and you need to keep in mind that no class signifies active, it is no longer evident that the element is active. We can utilize data attributes to solve this issue. This would cause the environment to seem like this:
<div data-active="true">...</div> <div data-active="false">...</div>
"js-". For example,
Top comments (2)
Appreciate the sentiment here having to try and clean up an e-commerce front end theme that the Dev has utilised your exact example of adding and removing classes with js. It's horrible checking through various states to see what classes are being added removed at any point in time, couple this with different breakpoints and media queries being used it's a nightmare.
I learnt a few rough lessons in js around mutation of variables and the mess you can get into. I feel as though messing with classes can actually lead you down the same path. I like the data attribute idea, you can clearly see what is being targeted and it's before / after state options.
Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍