What are the data-* attributes
A data attribute is just another plain attribute for any html tag, any attribute on any element whose attribute name starts with data- is a data attribute. You can save any kind of information on it.
Those attributes can be accesed with Javascript and CSS.
How to use data-* attributes
To add a data attribute we need :
- Some information to save
- Desire to live
Just add an attribute (like class="myclass") to the tag that you want. For example, in the following div some data will be saved to retrieve
<div id="randomid" data-articleid="123" data-maincategorie="articles" data-categories="[1,23,35,68,6]" data-gifpath="/path/to/gif.gif">
<h3>My article title</h3>
<p>
Article content
</p>
</div>
Accesing data attributes with Javascript
There are many ways to retrieve a data attribute with javascript :
High support javascript (recommended)
var domElement = document.getElementById('randomid');
var articleId = domElement.getAttribute('data-articleid');
console.log(articleId);//Outputs 123
We will use the native getAttribute function and we will give the complete name of the attribute including data-, this is available in all the browsers.
Javascript Datasets
As a html5 new feature, in the modern browsers you can retrieve a data attribute value using the dataset property. Type only the name without data-
var domElement = document.getElementById("randomid");
var articleId = domElement.dataset.articleid;
console.log(articleId);//Outputs 123
As you can see, the data has been translated to properties in the dataset object of the element.
jQuery
With jQuery we will use the .data() function. If you're using an older jQuery version you can use the .attr() function instead.
var $domElement = $('#randomid');
var articleId = $domElement.data('articleid');
console.log(articleId); // Outpusts 123
If you're using an older version use attr function and type the complete name including data-:
var $domElement = $('#randomid');
var articleId = $domElement.attr('data-articleid');
Accesing data attributes with CSS
As data attributes are plain HTML attributes, you can even access them from CSS.
To retrieve it with css use the attr() function, for example in this case the article id will be placed before the id with the following rule :
div::before {
content: attr(data-articleid);
}
To use these data attributes to customize with styles, use :
/**
* All the div's with data-maincategorie='articles' will have blue as background color
**/
div[data-maincategorie='articles'] {
background-color: blue;
}
Important notes :
- Don't save any sensitive information as this can be viewed in the source code.
- Don't use uppercase with data-* attributes (they will be forced to lowercase automatically but if you don't know this you'll waste time while trying to retrieve them with javascript with the wrong name).
- To support IE 10 and under you need to access data attributes with getAttribute().
- They're a great solution for mini datasets.