Data > Tag: HTML Explained
The “” tag in HTML is not a standard or recognized element in HTML5, HTML4, or any other widely accepted HTML version. However, it's crucial to understand that not all custom tags are invalid in HTML.
Custom data attributes can be added to any element using the "data-" prefix. These attributes allow us to store custom data private to the exising elements, misuse is a common practice for storing meta information.
Understanding HTML5 Custom Data Attributes
In HTML5, you can add custom data attributes to any standard or custom element. These attributes start with "data-" and can be used to store private data for the current and future use.
For example, you might use a data attribute to store user-ids, timestamps, or any other numerical data that doesn't fit into standard HTML elements.
Adding Custom Data Attributes
To add a custom data attribute, simply append it to any element like so: <p data-custom="value">. The name of the attribute should be an XML name, and the value is any string.
For more complex data, you can use multiple attributes or even JSON format. For instance, <p data-custom="{ "key":"value" }">. This allows you to store complex data structures.
Retrieving Custom Data Attributes
Browsers provide a way to access these data attributes using the "dataset" property. For instance, to access the "custom" attribute in our previous example, you'd use element.dataset.custom.
In JavaScript, you can then use this data to carry out dynamic operations based on the data.
Future-proofing Data in HTML
Using data attributes is a modern and standard way to include programming data in your HTML. It promotes separation of concerns: your HTML stays clean and your scripting stays uncluttered.
Moreover, attributes values are designed to be preserved during page transformations, thus ensuring the longevity of your data even with changes in your HTML structure.
Microdata and RDFa
Two other methods for embedding structured data into HTML are Microdata and RDFa. These are more complex but offer more flexibility and support for complex data structures.
We will explore them in detail in another post, but understanding data attributes is a crucial first step to being able to work with more complex data.
Now that you understand how to use and manage data in HTML, consider exploring other powerful tools for adding interactivity and depth to your web pages.