Member-only story
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.
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.
<ul>
<li id="one" data-uuid="1234-usg2345-23456-sgdsgd2" data-linked-product="45">Item 1</li>
<li id="two" data-uuid="4853-u3h2j75-s37kl-qq4sgd2" data-linked-product="5">Item 2</li>
<li id="three" data-uuid="7773-73h2j00-rs734-ii4slp8" data-linked-product="502">Item 3</li>
</ul>
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.
let element = document.getElementById("one")…