HTML5 is fairly new and it’s slowly being adopted by all web browsers today. A special feature of HTML5 is the ability to define custom data attributes. A data attribute is your own attribute that can contain information about an element. Let’s update our document to this.
<div id="myDiv" data-color="red">This is a div tag.</div>
To create a data attribute, you simply create an attribute with the data- prefix to the name of your attribute. In our case, we have a data attribute named data-color. Inside this attribute, you can store any kind of value you want. We store red in this attribute.
Let’s learn how to grab this in our script. Clear your script and add this bit of code.
var div = document.getElementById( 'myDiv' );
var color = div.dataset.color;
div.style.color = color
As usual, we grab the the element with the getElementById() method. We store this in a variable named div. Next, we create a variable that will store the data attribute we have in our div tag. To grab the data attribute, you access the dataset property. Inside this property, you can access all data attributes you created specific to an element.
Lastly, we update the CSS style of our div tag to the value inside our data-color attribute. You can create as many data attributes as you want. You can have any kind of values inside your data attributes.