Custom attributes in HTML correctly

When building web applications, it’s often quite useful to be able to have custom attributes on HTML tags. Custom attributes can be added to any HTML tag but there is a correct way to handle it and still maintain valid HTML. Doing this the correct way also makes it quite easy to make use of those custom attributes in Javascript code.

Photo by Christopher Robin Ebbinghaus on Unsplash

Let’s say you have a list of items and you want to only show a simple name in the visible list, yet you want to be able to reference an additional ID number or some other related information when it is clicked on or hovered over.

We can make use of data attributes to store additional information against each item in the list.

As you can see if this simple list, we have added to the list elements extra tags that begin with data-. These data tags are part of the HTML standard and are fully valid markup.

The best thing about these data attributes is how easy it is then to access the data using javascript.

As you can see in this javascript snippet, we can access those data attributes in native Javascript really easily using the dataset attribute of the element. The dataset attribute is a list containing all those data attributes in a simple to access way.

In the case of the data attribute data-linked-product, we access that using element.dataset.linkedProduct

As you can see, data attributes that have more than a single word with a separator will be accessible using camel case in the dataset.

You can also set the value of those data attributes in the same way.

So there you have it. A simple, and valid HTML way of adding additional custom properties to HTML elements and accessing or changing them easily in Javascript.

I used this recently to add the ability to sort a table. Using data attributes I could easily keep a reference of which way it was being sorted and the type of data we needed to sort. For example I was able to store the fact that a particular field had dates that had to be compared to sort correctly.

Self taught software developer, photographer and fiction writer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store