HTML & CSS - - By Gajendar Singh

How You Can Use HTML5 Custom Data Attributes and Why

HTML5 Custom Data Attributes

In this article, I am going to show you how you can use HTML5 custom data attributes. I’m also going to present you with some use cases that you can find helpful in your work as a developer.

Why Custom Data Attributes?

Very often we need to store information associated with different DOM elements. This information might not be essential for readers, but having easy access to it would make life a lot easier for us developers.

For instance, let’s say you have a list of different restaurants on a webpage. Before HTML5, if you wanted to store information about the type of food offered by restaurants or their distance from the visitor, you would have used the HTML class attribute. What if you also needed to store the restaurant id to see which particular restaurant the user would want to visit?

Here are a few problems with the approach based on the HTML class attribute.

  • The HTML class attribute is not meant to store data like this. Its main purpose is to allow the developer to assign style information to a set of elements.
  • Each additional piece of information requires us to add a new class to our element. This makes it harder to parse the data in JavaScript to actually get what we need.
  • Let’s say a given class name begins with numbers. If you decide to later style the elements based on that data in the class name, you will have to either escape the number or use attribute selectors in your stylesheet.

To get rid of these issues, HTML5 has introduced custom data attributes. All attributes on an element whose name starts with data- are data attributes. You can also use these data attributes to style your elements.

Next, let’s dive into the basics of data attributes and learn how to access their values in CSS and JavaScript.

The HTML Syntax

As I mentioned earlier, the name of a data attribute will always start with data-. Here is an example:

<li data-type="veg" data-distance="2miles" data-identifier="10318">
  Salad King
</li>

You can now use these data attributes to search and sort restaurants for your visitors. For example, you can now show them all the vegetarian restaurants within a certain distance.

Besides the data- prefix, the name of a valid custom data attribute must contain only letters, numbers, hyphen (-), dot (.), colon (:) or underscore (_). It cannot contain capital letters.

There are two things that you should keep in mind when using data attributes.

First, data stored in these attributes should be of type string. Anything that can be string-encoded can be stored in data attributes as well. All the type conversions will need to be done in JavaScript.

Second, data attributes should only be used when there are no other appropriate HTML elements or attributes. For example, it is not appropriate to store an element’s class in data-class attribute.

An element can have any number of data attributes with any value you want.

Data Attributes and CSS

You can use data attributes in CSS to style elements using attribute selectors. You can also show the information stored in the data attribute to users (in a tooltip or some other way) with the help of the attr() function.

Styling Elements

Getting back to our restaurant example, you can give users a cue about the type of restaurant or its distance from them using attribute selectors to style the background of the restaurants differently. Here is an example:

li[data-type='veg'] {
  background: #8BC34A;
}

li[data-type='french'] {
  background: #3F51B5;
}

See the Pen Styling elements with data attributes by SitePoint (@SitePoint) on CodePen.

Creating Tooltips

You can use tooltips to show users some additional information related to an element.

I recommend you use this method for quick prototypes rather than a production website, not least because CSS-only tooltips are not fully accessible.

The information that you want to show can be stored in a data-tooltip attribute.

<span data-tooltip="A simple explanation">Word</span>

You can then present the data to the user with the ::before pseudo element.

span::before {
  content: attr(data-tooltip);
  // More Style Rules
}

span:hover::before {
  display: inline-block;
}

See the Pen Creating tooltips with data attributes by SitePoint (@SitePoint) on CodePen.

Accessing Data Attributes with JavaScript

There are three ways of accessing data attributes in JavaScript.

Using getAttribute and setAttribute

You can use getAttribute() and setAttribute() in JavaScript to get and set the value of different data attributes.

The getAttribute method will either return null or an empty string if the given attribute does not exist. Here is an example of using these methods:

var restaurant = document.getElementById("restaurantId");
var ratings = restaurant.getAttribute("data-ratings");

You can use the setAttribute method to modify the value of existing attributes or to add new attributes.

restaurant.setAttribute("data-owner-name", "someName");

Using the dataset Property

A simpler method of accessing data attributes is with the help of the dataset property. This property returns a DOMStringMap object with one entry for each custom data attribute.

There are a few things that you should keep in mind while using the dataset property.

It takes three steps to transform a custom data attribute into a DOMStringMap key:

  • The data- prefix is removed from the attribute name
  • Any hyphen followed by a lower case letter is removed from the name and the letter following it is converted to uppercase
  • Other characters will remain unchanged. This means that any hyphen that is not followed by a lowercase letter will also remain unchanged.

The attributes can then be accessed using the camelCase name stored in the object as a key like element.dataset.keyname.

Another way of accessing the attributes is using bracket notation, like element.dataset[keyname]

Consider the following HTML:

<li data-type="veg" data-distance="2miles" data-identifier="10318" data-owner-name="someName">
  Salad King
</li>

Here are a few examples:

var restaurant = document.getElementById("restaurantId");

var ratings = restaurant.dataset.ratings;
restaurant.dataset.ratings = newRating;

var owner = restaurant.dataset['ownerName'];
restaurant.dataset['ownerName'] = 'newOwner';

This method is now supported in all major browsers and you should favor it over the previous method for accessing custom data attributes.

Using jQuery

You can also use the jQuery data() method to access data attributes of an element. Before jQuery version 1.6, you had to use the following code to access data attributes:

var restaurant = $("#restaurantId");

var owner = restaurant.data("owner-name");
restaurant.data("owner-name", "newName");

From version 1.6, jQuery started using the camelCase version of data attributes. Now, you can do the same thing using the following code:

var restaurant = $("#restaurantId");

var owner = restaurant.data("ownerName");
restaurant.data("ownerName", "newName");

You should know that jQuery also tries to internally convert the string obtained from a data attribute into a suitable type like numbers, booleans, objects, arrays and null.

var restaurant = $("#restaurantId");
var identifier = restaurant.data("identifier");

console.log(typeof identifier);
// number

If you want jQuery to get the value of an attribute as a string without any attempt to convert it into other types, you should use jQuery’s attr() method.

jQuery only retrieves the value of data attributes the first time they are accessed. The data attributes are then no longer accessed or changed. All the changes that you make to those attributes are made internally and accessible only within jQuery.

Let’s assume you are manipulating the data attributes of the following list item:

<li id="salad" data-type="veg" data-distance="2miles" data-identifier="10318">
  Salad King
</li>

You can use the code below to change the value of its data-distance attribute:

var distance = $("#salad").data("distance");
console.log(distance);
// "2miles"

$("#salad").data("distance","1.5miles");
console.log(distance);
// "1.5miles"

document.getElementById("salad").dataset.distance; 
// "2miles"

As you can see, accessing the value of the data-distance attribute using vanilla JavaScript (not jQuery) keeps giving us the old result.

Conclusion

In this tutorial I have covered all the important things that you need to know about HTML5 data attributes. Besides creating tooltips and styling elements using attribute selectors, you can use data attributes to store and show users some other data like a notification about unread messages and so on.

If you have any other questions about data attributes, let me know in the comments.

Sponsors