Data attributes allows us to store custom data on HTML element.
We create data attributes by adding name to data hyphen( data- ).
<div class=”button” data-filter = “dc”>DC</div>
Here filter is attribute name. It should always be lowercase letters.
In this example attribute value is dc. Value of data attribute should always be string i.e you cannot assign number or boolean to data attribute.
How to get the data attributes of an element using JavaScript ?
<ul>
<li data-filter = “dc”>DC</li>
<li data-filter = “marvel”>Marvel</li>
</ul>
let filterList = document.querySelector(‘ul’).children;
console.log(filterList[0].dataset.filter) //dc
console.log(filterList[1].dataset.filter) // marvel
Or you can use getAttribute() method
console.log(filterList[0].getAttribute(‘data-filter’)); //dc
console.log(filterList[1].getAttribute(‘data-filter’)); //marvel
Beware that some older browsers do not support dataset.
How to access data attributes in CSS?
There are again two ways you can target data attributes.
-attribute selector
-attr() css function
<ul>
<li data-filter = “dc”>DC</li>
<li data-filter = “marvel”>Marvel</li>
</ul>
Using attribute selector
li[data-filter=”dc”]{
color: #0476f2;
}
li[data-filter=”marvel”]{
color: #e50e18;
}
Using attr()
li{
content: attr(data-filter);
color: #0476f2;
}
Project Example
Here is a simple example that filters list. It has minimal css styling. In this example you can see how you can pass information about HTML element to javascript with data attributes.
*Lines from 23-29* shows how you can fetch data-attributes for styling. I have commented them because in our code example, I have used class attribute ‘dc’ and ‘marvel’ for styling.
Finally this is how the code looks.
If you click DC button , it lists DC character.
If you click Marvel button, it lists Marvel Character.
All button lists all the items.