On this article, I’m going to point out you ways you need to use HTML5 customized knowledge attributes. I am additionally going to current you with some use instances that you’ll find useful in your work as a developer.
Why Custom Data Attributes?
Fairly often we have to retailer info related to totally different DOM parts. This info won’t be important for readers, however having quick access to it might make life so much simpler for us builders.
For example, as an instance you have got an inventory of various eating places on a webpage. Earlier than HTML5, for those who needed to retailer details about the kind of meals provided by eating places or their distance from the customer, you’d have used the HTML
class attribute. What should you additionally wanted to retailer the restaurant
id to see which specific restaurant the consumer would need to go to?
Listed here are a number of issues with the HTML class-based mostly strategy.
- Courses will not be meant to retailer knowledge like this. Their principal function is to permit the developer to assign fashion info to a set of parts.
- For example a given class identify begins with numbers. In case you determine to later fashion the weather based mostly on that knowledge within the class identify, you’ll have to both escape the quantity or use attribute selectors in your stylesheet.
To eliminate these points, HTML5 has launched customized knowledge attributes. All attributes on a component whose identify begins with
knowledge- are knowledge attributes. You also can use these knowledge attributes to type your parts.
The HTML Syntax
As I discussed earlier, the identify of a knowledge attribute will all the time begin with
knowledge-. Right here is an instance:
You can now use these knowledge attributes to look and type eating places in your guests. For instance, now you can present all of them the vegetarian eating places inside a sure distance.
The identify of a legitimate customized knowledge attribute all the time begins with the prefix
knowledge-. Additionally, the identify should solely include letters, numbers, hyphen (-), dot (.), colon (:) or underscore (_). It can’t include capital letters.
There are two issues that it is best to have in mind when utilizing knowledge attributes.
Second, knowledge attributes ought to solely be used when there are not any different applicable HTML parts or attributes. For instance, it isn’t applicable to retailer a component’s
A component can have any variety of knowledge attributes with any worth you need.
Proceed studying %How You Can Use HTML5 Custom Data Attributes and Why%