Score code, devs, and debt fast.
Score code, devs, and debt fast.

7 Day Free Trial. Cancel Anytime.
Data attributes allow developers to store custom data in HTML elements. They provide a way to add extra information to HTML elements that can be used by JavaScript or CSS to add functionality to a webpage. In this article, we will cover what data attributes are and what they are used for.
Very often we need to store information associated with different DOM elements. This information might not be essential for readers, but having easy access to it would make life a lot easier for us developers.
For instance, let’s say you have a list of different restaurants on a webpage. Before HTML5, if you wanted to store information about the type of food offered by restaurants or their distance from the visitor, you would have used the HTMLclass attribute. What if you also needed to store the restaurantid to see which particular restaurant the user would want to visit?
Here are a few problems with the approach based on the HTML class attribute.
To get rid of these issues, HTML5 has introducedcustom data attributes. All attributes on an element whose name starts withdata- are data attributes. You can also use these data attributes to style your elements.
Next, let’s dive into the basics of data attributes and learn how to access their values in CSS and JavaScript.
As I mentioned earlier, the name of a data attribute will always start withdata-. Here is an example:
<li data-type="veg" data-distance="2miles" data-identifier="10318">
Salad King
</li>
You can now use these data attributes to search and sort restaurants for your visitors. For example, you can now show them all the vegetarian restaurants within a certain distance.
Besides thedata- prefix, the name of a valid custom data attribute must contain only letters, numbers, hyphen (-), dot (.), colon (:) or underscore (_). It cannot contain capital letters.
There are two things that you should keep in mind when using data attributes.
First,data stored in these attributes should be of type string. Anything that can be string-encoded can be stored in data attributes as well. All the type conversions will need to be done in JavaScript.
Second, data attributes shouldonly be used when there are no other appropriate HTML elements or attributes. For example, it is not appropriate to store an element’sclass indata-class attribute.
An element can have any number of data attributes with any value you want.
You can use data attributes in CSS to style elements using attribute selectors. You can also show the information stored in the data attribute to users (in a tooltip or some other way) with the help of theattr() function.
Getting back to our restaurant example, you can give users a cue about the type of restaurant or its distance from them using attribute selectors to style the background of the restaurants differently. Here is an example:
li[data-type='veg'] {
background: #8BC34A;
}li[data-type='french'] {
background: #3F51B5;
}
See the PenStyling elements with data attributes by SitePoint (@SitePoint) onCodePen.
You can use tooltips to show users some additional information related to an element.
I recommend you use this method for quick prototypes rather than a production website, not least becauseCSS-only tooltips are not fully accessible.
The information that you want to show can be stored in adata-tooltip attribute.
<span data-tooltip="A simple explanation">Word</span>
You can then present the data to the user with the::before pseudo element.
span::before {
content: attr(data-tooltip);
// More Style Rules
}span:hover::before {
display: inline-block;
}
See the PenCreating tooltips with data attributes by SitePoint (@SitePoint) onCodePen.
There are three ways of accessing data attributes in JavaScript.
You can usegetAttribute() andsetAttribute() in JavaScript to get and set the value of different data attributes.
ThegetAttribute method will either returnnull or an empty string if the given attribute does not exist. Here is an example of using these methods:
let restaurant = document.getElementById("restaurantId");
let ratings = restaurant.getAttribute("data-ratings");
You can use thesetAttribute method to modify the value of existing attributes or to add new attributes.
restaurant.setAttribute("data-owner-name", "someName");
A simpler method of accessing data attributes is with the help of thedataset property. This property returns aDOMStringMap object with one entry for each custom data attribute.
There are a few things that you should keep in mind while using thedataset property.
It takes three steps to transform a custom data attribute into aDOMStringMap key:
data- prefix is removed from the attribute nameThe attributes can then be accessed using the camelCase name stored in the object as a key likeelement.dataset.keyname.
Another way of accessing the attributes is using bracket notation, likeelement.dataset[keyname]
Consider the following HTML:
<li data-type="veg" data-distance="2miles" data-identifier="10318" data-owner-name="someName">
Salad King
</li>
Here are a few examples:
var restaurant = document.getElementById("restaurantId");var ratings = restaurant.dataset.ratings;
restaurant.dataset.ratings = newRating;
var owner = restaurant.dataset['ownerName'];
restaurant.dataset['ownerName'] = 'newOwner';
This method is nowsupported in all major browsers andyou should favor it over the previous method for accessing custom data attributes.
You can also use the jQuerydata() method to access data attributes of an element. Before jQuery version 1.6, you had to use the following code to access data attributes:
var restaurant = $("#restaurantId");var owner = restaurant.data("owner-name");
restaurant.data("owner-name", "newName");
From version 1.6, jQuery started using the camelCase version of data attributes. Now, you can do the same thing using the following code:
var restaurant = $("#restaurantId");var owner = restaurant.data("ownerName");
restaurant.data("ownerName", "newName");
You should know that jQuery also tries to internally convert the string obtained from a data attribute into a suitable type like numbers, booleans, objects, arrays and null.
var restaurant = $("#restaurantId");
var identifier = restaurant.data("identifier");console.log(typeof identifier);
// number
If you want jQuery to get the value of an attribute as a string without any attempt to convert it into other types, you should use jQuery’sattr() method.
jQuery only retrieves the value of data attributes the first time they are accessed. The data attributes are then no longer accessed or changed. All the changes that you make to those attributes are made internally and accessible only within jQuery.
Let’s assume you are manipulating the data attributes of the following list item:
<li data-type="veg" data-distance="2miles" data-identifier="10318">
Salad King
</li>
You can use the code below to change the value of itsdata-distance attribute:
var distance = $("#salad").data("distance");
console.log(distance);
// "2miles"$("#salad").data("distance","1.5miles");
console.log(distance);
// "1.5miles"
document.getElementById("salad").dataset.distance;
// "2miles"
As you can see, accessing the value of thedata-distance attribute using vanilla JavaScript (not jQuery) keeps giving us the old result.
In this tutorial I have covered all the important things that you need to know about HTML5 data attributes. Besides creating tooltips and styling elements using attribute selectors, you can use data attributes to store and show users some other data like a notification about unread messages and so on.
HTML5 custom data attributes provide a powerful way to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, extra properties on DOM, or Node.setUserData(). They allow you to store additional information on HTML elements without needing to use a separate CSS class or ID. This can be particularly useful when you need to store information for scripting, such as the ID of a linked record from a database.
You can access custom data attributes in JavaScript using the dataset property. This property gives you access to all the data attributes on an element as a JavaScript object. For example, if you have an element with the attribute data-test=”value”, you can access it in JavaScript with element.dataset.test.
Custom data attributes must be named with the prefix ‘data-‘, followed by at least one character. The attribute name should not contain any uppercase letters, and must be at least one character long after the ‘data-‘ prefix. The attribute name should not contain any semicolons.
While custom data attributes can be extremely useful, they are not intended to store large amounts of data. They are best used for small amounts of data that are specific to a particular element and can be kept in sync with the HTML that they are associated with.
Yes, custom data attributes can be used on all HTML elements. However, they are not appropriate for storing content that should be visible and accessible in the HTML, as this would not be semantically correct and could lead to accessibility issues.
You can set custom data attributes in JavaScript using the setAttribute method. For example, if you want to set a custom data attribute ‘data-test’ to ‘value’ on an element, you can do so with element.setAttribute(‘data-test’, ‘value’).
Yes, you can use custom data attributes in your CSS to style elements based on their custom data. This can be done using the attribute selectors in CSS.
Yes, custom data attributes are case-sensitive. The attribute name should be written in lower case.
You can use any characters in the value of a custom data attribute, but you should be aware that some characters may need to be escaped in the HTML. The attribute name should not contain any semicolons.
Custom data attributes are part of the HTML5 specification and are supported in all modern browsers. However, they may not be fully supported in older browsers, so you should test your code thoroughly if you need to support older browsers.
7 Day Free Trial. Cancel Anytime.