HTML5 Data Attributes

As a recent graduate of Flatiron School’s Web Development Bootcamp, I have been job seeking for the past few weeks and working on improving my CSS/HTML skills. This week I discovered Data Attributes, so that’s what we’ll talk about today.

What are Data Attributes?

Developer-Mozilla definition says:

data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, extra properties on DOM, or Node.setUserData().

In other words, data attributes are intended to store custom data within the application that will not be displayed to the reader but will be very useful to the developer.

How to use Data Attributes?

The attribute name must begin with the prefix data- and must be at least one character long after it. The name must contain only letters, numbers, hyphen (-), dot (.), colon (:) or underscore (_). It cannot contain uppercase letters.

You can assign as many custom data attributes to an element as you want, but keep in mind that you should only use data attributes when there are no other appropriate HTML elements or attributes.

When should you use Data Attributes?

Whenever you need to add extra info on an element, for example if you have a list of elements and you want to be able to filter/order them.

Let’s see sitepoint example:

Here by adding custom data attributes to a list of restaurant, you will be able to search and sort restaurants for your visitors. For example, you can show only vegetarian restaurant in a specific distance.

How to use Data Attributes with CSS?

Data Attributes should not be used specifically for styling purposes, but sometimes it can be appropriate. Getting back to the restaurant example, you could apply different background colors depending on the restaurant type.

Once you know how to access the element through its data attributes, you can apply any styling.

How to use Data Attributes with Javascript?

You can use getAttribute() to access the value of some attributes:

You can use setAttribute() to modify or add an attribute:

You can also access attributes value through the dataset object. In that case you get the property by the name of the attribute (after data-) **note that dashes are converted to camelCase :

You can also update a attributes value through the dataset object:

article.dataset.columns = 5 would change that attribute to "5".

And that’s it for our quick introduction to HTML5 Data Attributes. Below are some useful articles for more detailed explanations: