Tuesday , 18 June 2019
Home / Programming / JavaScript / Data Attribute – Advanced JavaScript Tutorial
Data Attribute
Data Attribute

Data Attribute – Advanced JavaScript Tutorial

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.

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.

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.


The most common reason for using data attributes is so that you store information about the web page or information about an element. A common example is slideshows. You can have the user customize the x and y positions of a slide. Same thing goes for the animation. They won’t have to know any JavaScript in order to customize the slideshow. The data attribute only works in Google Chrome and Safari. It’s still relatively new. For more information about data attributes, then go here.


About Jasko Koyn

Check Also


Audio – Advanced JavaScript Tutorial

The video and audio objects both have the same events, properties and methods. So, you …

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.