Using HTML data attributes in JavaScript and CSS

OpenJavaScript 0
Reading Time: 3 minutes 🕑

Last updated: August 21, 2022.

With HTML5 data-* attributes, you can store data on the attribute of a HTML element.

You must be able to express the data in string format to use this feature.

In this tutorial, we cover data attributes in HTML and how their values can be set and retrieved using JavaScript. We also cover how to use data attributes in CSS.

Table of contents

Data attributes in HTML

To create a data attribute in HTML, specify an attribute name that starts with data-.

Some possible examples : data-fav-color, data-url, data-user-status.

To assign a value, do so in the normal way you would for any element attribute:

<div data-fav-color="blue", data-user-status="member" mood="happy"></div>

You may already be aware that you can create custom attributes in HTML5. In the above, the attribute mood has been created as a custom attribute, but not a data-* attribute.

So what’s so special about data-* attributes?

The main reason is that there are convenient ways of working with data attributes in JavaScript – especially if there are multiple attributes.

Accessing and setting data attributes in JavaScript

Data attributes are accessible in JavaScript via the dataset property:

<div data-fav-color="blue", data-user-status="member" mood="happy"></div>

<script>

const div = document.querySelector('div');

console.log(div.dataset);
{
    "favColor": "blue",
    "userStatus": "member"
}

</script>

Notice that in the returned object, the non-data attribute mood is not included.

Also notice that the data attribute names have been automatically converted to camel case!

This makes them individually accessible on the dataset object via dot notation:

<div data-fav-color="blue", data-user-status="member" mood="happy"></div>

<script>

const div = document.querySelector('div');
    
console.log(div.dataset.favColor); // blue

div.dataset.userStatus = "guest";
console.log(div.dataset.userStatus); // guest

</script>

Alternatively, you can also set and get a data attribute using setAttribute() and getAttribute():

const span = document.createElement('span');
    
span.setAttribute('data-status', 'online');

span.getAttribute('data-status'); // online

Extracting data from dataset property

Thanks to the dataset property, you can access all data attributes on an element without having to write code to access them individually.

To make the data easier to work with, you can extract the values, key and values or keys only using methods available on the native Object constructor object.

<div data-fav-color="blue", data-user-status="member" mood="happy"></div>

<script>

const div = document.querySelector('div');
    
Object.values(div.dataset);
// [
//     "blue",
//     "member"
// ]

Object.entries(div.dataset);
// [
//     [
//         "favColor",
//         "blue"
//     ],
//     [
//         "userStatus",
//         "member"
//     ]
// ]   

Object.keys(div.dataset);
// [
//     "favColor",
//     "userStatus"
// ]

</script>

The result is the data now stored in array format to which you can apply iterable methods, such as loops and map() and others.

Converting non-string data

Only string data (or data than can be coerced to string data) can be stored in a data attribute.

If you want to store more complex native JavaScript data types, you can do so by converting them to a string using JSON.stringify(). Then, you can read data from an attribute using JSON.parse().

<div data-fav-color="blue", data-user-status="member" mood="happy"></div>

<script>

const div = document.querySelector('div');

const data = [[true, "Ted"],[false, "James"],[null, "Jenny"]];

div.dataset.complexData = JSON.stringify(data);

console.log(div); 
// 

const readData = JSON.parse(div.dataset.complexData);

console.log(readData)
// [
//     [
//         true,
//         "Ted"
//     ],
//     [
//         false,
//         "James"
//     ],
//     [
//         null,
//         "Jenny"
//     ]
// ]

</script>

Removing a data attribute

To remove a data attribute from an element in the DOM, use the removeAttribute() method on the respective element, passing in the full name of the data attribute you wish to remove:

const span = document.createElement('span');
    
span.dataset.favMovie = "Weekend at Bernies";
console.log(span.hasAttribute('data-fav-movie')); // true

span.removeAttribute('data-fav-movie');
console.log(span.hasAttribute('data-fav-movie')); // false

Data attributes in CSS

You can access data attributes in CSS with the attr function:

div::before {
    content: attr(data-user-status);
}

Or using the attribute selector:

div[data-fav-color='blue'] {
    background-color: blue;
}
div[data-fav-color='red'] {
    background-color: red;
}

Related links