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.
<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>
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.
let element = document.getElementById("one");
console.log(element.value + " has a UUID of " + element.dataset.uuid + " and a linked product id of " + element.dataset.linkedProduct);
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.
element.dataset.linkedProduct = 102;
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.