How HTML Data-* Attributes work?
HTML5 Data Attribute: This data attribute gives the potential of binding specific information to particular section. Information when attached can be called via JavaScript rather than calling this from server side Ajax or database calls. One can also apply specific CSS to get the data being presented in custom way. Data attributes can be applied to all elements.
HTML Data Attribute Syntax
— Where * can be any custom string value to match your content information
HTML Data Attributes Example
Here is active example for using data attribute with JavaScript:
Species
Click on a species to see what type it is:
- Sparrow
- Tuna
- Black Widow
As per usage value can be anything string, must be one character long after prefix data*- and uppercase are not allowed at all.
HTML Data Attribute Javascript Access
You can easily read these attributes with JavaScript as well to use them further. With getAttribute and setAttribute you can get the value of these data attributes. In the above example we have used JavaScript to get the browser notification as you click on the line.
var animalType = animal.getAttribute("data-animal");
HTML Data Attribute CSS Access
These Data attributes are part of HTML attributes only and you can apply CSS on them on present them to match your site design. Here is quick example of using CSS Selector in Data Attribute to change the layout of the design.
li[data-animal="bird"] {background: #8BC34A;} li[data-animal="fish"] {background: red;} li[data-animal="spider"] {background: yellow;}
HTML Data Attribute Case Sensitivity
All tags and attributes in HTML are case insensitive but it is recommended them to use them in lowercase from the beginning.
- name must not begin with xml
- name must not have any semicolon (U+003A)
- name must not contain capital A to Z letters
These data attributes if used in capital gets lowered ASCII-lowercased automatically so the restriction doesn’t affect documents at all. Though modern browsers will rectify these can cause error in the markup so avoid using them in capitalise.
Also Check Out