Beginner's guide to data-attributes in CSS
Arindam Chowdhury
Posted on February 2, 2023
What are data-attributes?
They are custom HTML attributes, that you can use on any HTML elements. You just need to prefix those custom attributes with data-.
It's recommended not to make your own attributes, i.e., creating attributes which are not prefixed with data-.
Syntax
You can use anything after data-. And one HTML element can have multiple data attributes.
<div data-category='cars' data-type='luxury'>
Audi
</div>
<div data-category='laptop'>
Lenovo
</div>
Use Cases
Javascript
Suppose you want to add custom icons, based on the data-category.
- You can access data-attributes via
getAttribute(attribute-name)
const data = document.querySelectorAll("[data-category]");
data.forEach((item) => {
console.log(item.getAttribute("data-category"))
// cars or laptop will be the output
// Add icons based on cars or laptop
})
- You can also access them via
dataset
property.
If you console.log(item.dataset)
, you'll see all the data-attributes for that HTML element, in an object.
const data = document.querySelectorAll("[data-category]");
data.forEach((item) => {
console.log(item.dataset.category)
// cars or laptop will be the output
// Add icons based on cars or laptop
});
After adding the required Javascript, this is how it looks
CSS
Now, if we want to add custom designs to the elements, based on the data-attributes, we can select them in CSS using the attribute-selector.
[data-category="cars"] {
background: #feffd4 ;
}
After, adding the required CSS, this is how it looks
Further Readings:
Posted on February 2, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.