If you have been doing web development for any amount of time then you have most likely run across or written code that looks like this
What Are Data Attributes?
That better way to select elements is by using data attributes. If you are not familiar with data attributes they are essentially custom attributes that you can add to any HTML element, and they will always start with
data-. For example you could have an element like this
<div data-accordion-container>...</div> which has the
data-accordion-container attribute. You can also specify values for these custom data attributes like this
<div data-children-count="3">...</div>. I don’t want to go too in depth into what data attributes are since that is not the focus of this article so if you want some more information you can checkout the amazing MDN docs. So now that I have explained what data attributes are, let me explain why you should be using them to select elements instead of classes.
The first and most obvious reason is that you can be more expressive in your selectors. Since a data attribute can have a value you can use that value in the selector to make easy dynamic selectors. For example, let’s imagine we have an element that can toggle between active and inactive when clicked on. If we used a class based approach we would need to have a class for active and inactive which would lead us to have elements that look like this:
<div class="active">...</div> <div class="inactive">...</div>
<div>...</div> <div class="inactive">...</div>
The problem with this approach is that now it is not obvious that the element is active since there is no class denoting it as active and you need to remember that no class means active. In order to fix this problem we can use data attributes. This would make the elements look like this
<div data-active="true">...</div> <div data-active="false">...</div>
js-. For example