What are custom attributes in HTML5 ?
Custom attributes are attributes that are not part of the standard HTML5 attributes but are explicitly created. They allow us to add our own information to HTML tags. These are not specific and can be used with all the HTML elements. The extra information stored through custom attributes are data that need not have any defined meaning. These data are private to the page or application. The custom attributes are also known as data attributes.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Two parts of the custom attributes:
- Attribute Name – The attribute name must be at least one character long after the prefix “data-“. It should not contain any upper case letters.
- Attribute Value – The value to be stored can be any string.
custom_attributes.js: Whenever an item is clicked this code snippet will be triggered. Here we will alert the type of food that is stored in the custom attribute using the dataset property. The code snippet looks like this:
Example 3: In this example, we will set the background colors of the elements using the CSS access that we just saw. As the custom attributes are plain HTML attributes, they can be accessed from CSS. For example, we can use attribute selectors to style the background color of the element.
styles.css: Select the elements in the styles.css file and set the background color of the elements using standard CSS properties.