I would like to say Hearty Thanks to HTML5, because we now have the ability to attach on all html elements you would like, whether it be metadata about a dimensions, latitude, longitude, custom height, and weight etc.
Best of all, it can be available in nearly every web browsers, since they can be easily grabbed with & .
This features give developers the flexibility to embed all sorts of information in their markup. It will be very useful on drawing canvas in HTML5
HTML5 Data Attributes Structure
It consists of two parts
- Attribute Name
- The data attribute name must be at least one character long and must be prefixed with ‘‘. It should not contain any uppercase letters.
- Attribute Value – It can be any string
Using the above syntax, we can attach the custom data attributes with values as shown below
<a href="#" class="details" data-sitename="w3lessons" data-link="http://w3lessons.info" data-founder="Karthikeyan" data-tags="php,html5,css3,jQuery" id="details" />Site Details</a>
If you click on Site Details, you will get the following values by accessing those attributes
- sitename – w3lessons
- link – http://w3lessons.info
- founder – Karthikeyan
- tags – php,html5,css3,jQuery
// Getting data-attributes using getAttribute
var site_details = document.getElementById('details');
var sitename = site_details.getAttribute('data-sitename');
// sitename = 'w3lessons'
// Setting data-attributes using setAttribute
//new sitename = 'w3lessons.info'
Accessing data- attributes with jQuery
var site_details = $(this).attr("data-sitename");
var site_founder = $(this).attr("data-founder");
var site_tags = $(this).attr("data-tags");
alert(site_details + site_founder + site_tags);
In this tutorial, We have used custom data attributes to provide additional information to a client-side script. It’s a creative approach to many problems and its a perfect solution to use these attributes.
The custom data attributes won’t hang up the browser and your code will be valid since you are using valid HTML5 doctype, since the attributes that start with data- with all be ignored.