Post 1

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:

BIENVENIDOS A SATORMEDICAL

Líderes en explotación compartida.