Many a times we need to store/require additional data from HTML elements for parsing or performing some operations.
This can be achieved using a class or rel attributes that traditional HTML provides. But it can take a lot of effort and tedious JavaScript code to get the such extra data from these HTML elements.
What is Html5 Custom Attributes
Html5 Custom Attributes are data attributes used to store custom/additional data for the HTML element.
Rules to define Custom Attributes
1. The attribute name should start with data-
2. The attribute name should contain atleast one letter word after data-
3. The attribute name should be in lowercase.
4. The attribute value can be any string.
e.g
1 |
<div id="car" data-model="polo" data-year="2014">Volkswagen</div> |
Getting Data stored in the Custom Attributes
JavaScript
1 2 3 |
var carDetail = document.getElementById('car'); carDetail.getAttribute("data-model"); // returns polo carDetail.getAttribute("data-year"); // returns 2014 |
jQuery
1 2 |
$("#car").attr("data-model"); $("#car").attr("data-year"); |
Use of HTM5 Custom Attributes in Select box
In a select box, the HTML5 custom attributes can be useful in storing extra data, which can be used later whenever a change event is triggered on the select box.
E.g If a select box has a list of employees and we need to get the details of the selected employee i.e. manager and department , traditional way to do is to get the employee id and make a ajax call to the server to get data.
But using the HTML5 custom attributes we can store the extra data in the element itself and use when required.
1 2 3 4 5 6 |
<select id="employees" onChange="displayEmployeeDetails()"> <option value="1" data-department="ABC Dept" data-manager="Manager1">Employee 1</option> <option value="2" data-department="ABC Dept" data-manager="Manager2">Employee 2</option> <option value="3" data-department="XYZ Dept" data-manager="Manager3">Employee 3</option> <option value="4" data-department="123 Dept" data-manager="Manager4">Employee 4</option> </select> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// using Old JavaScript function displayEmployeeDetails(){ var empDetails = document.getElementById("employees"); var selEmp = empDetails.options[empDetails.selectedIndex]; selEmp.getAttribute("data-department"); selEmp.getAttribute("data-manager"); } // using jQuery $(function(){ $("#employees").change(function(){ var selEmp = $(this).find('option:selected'); var department = selEmp.data('department'); var manager = selEmp.data('manager'); }); }); |