Note: If you've worked mainly with React, the className prop on a component generates an HTML class attribute when your component renders.
You can create non-standard attributes, like item or productId that will work, but if you want to access them, you would have to access them via the attribute getter, e.g.
// Get the awesome product HTML element.const someElement = document.querySelector('#awesome-product');// get attribute returns the value or if there is none, it returns nullconst productId = someElement.getAttribute('productId');
If you have a lot of these bespoke attributes, you'll always have to use .getAttribute().
Insert "There must be a better way" GIF here. 🤣
There is a better standard way to go about this, data attributes. Data attributes are a standard part of HTML. All you need to do is have them begin with data- and if the rest of the attribute is more than one word, separate them with hyphens.
For example, our productId would now become data-product-id. That looks like many extra characters, and we're still using .getAttribute.
So for example, if I wanted to get the value of the data-product-id attribute, I can do the following:
// Get the awesome product HTML element.const someElement = document.querySelector('#awesome-product');const productId = someElement.dataset.productId
So a few things are happening under the hood. All the data attributes when accessed via the dataset property no longer have data- in their names, and when the attribute has more than one word in it like data-product-id, it gets converted to camel case, productId.
The real power of this is if there are several of these attributes on an element, they're all available under the dataset property.
As mentioned at the beginning, I'm currently using a data attribute in the graph I made, but if you happen to be reading this on dev.to, they leverage data attributes quite a bit.
If you use the browser tools to inspect the home page of DEV, you'll see that the body HTML element is jam packed with data attributes.
State management libraries are definitely useful in certain contexts, but sometimes leveraging what the platform gives you, like data attributes, can be beneficial for your use case.