What Are Data Attributes?
I want to show you in very simple terms exactly what the HTML 5 Data Attributes are and how you can use them in your Development Workflow. Data Attributes are simple data tags that let you store and retrieve data based on the element they are attributed to.
They look very similar to the standard Class and ID attributes in your html but they are unique to you. You get to name them whatever you want depending on their use.
As you can see you can name the data attribute anything you like. As long as it is lowercase and prefixed with data-
//Div with class <div class="myClassName"></div> //Div with ID <div id="myId"></div> //Div with Data Attribute <div data-something="my_data_attribute_value"></div>
Data Attribute Example
Let me show you a practical example of setting data attributes. Then we will use jQuery to get the values of the Data Attributes and print them to the page.
Lets create a div in HTML and add some custom Data attributes like so:
<div data-years="5" id="profile"> Brian Revie has been a developer for: <span id="result"></span> </div>
As you can see we have added a custom data attributes to the Div. I have also provided an ID of ‘profile’ for the reason that we need to target this Div specifically with jQuery.
- Target The Results Span with jQuery
- Change the Results Span Text to add how many years I have been developing.
<script> $("#result").text( $("#profile").data("years") + " years" ); </script>
What we have done here in simple terms is using jQuery we are first targeting the element with an ID of result. We are then telling jQuery to add the text we want inside this element, the text we want is received by targeting the element with an ID of profile then in the profile element find a data attribute that has ‘years‘. (data-years)
This will print out the value of this data attribute value which is 5 then we are simply concatenating the word years by adding the + ” years” The resulting HTML you will see printed out on the screen is:
Brian Revie has been a developer for: 5 years
As you can see this is a very basic example of how you can use data attributes. You can do a lot with the data-attribute. It can be very helpful when you need to store and retrieve specific data.
Experiment and have fun with it. I hope this simple tutorial has given you a better insight into HTML 5 Data Attributes.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport"content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible"content="ie=edge"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <title>HTML 5 Data Attributes</title> </head> <body> <div data-years="5"id="profile"> Brian Revie has been a developer for: <span id="result"></span> </div> <script> $("#result").text( $("#profile").data("years") + " years"); </script> </body> </html>