HTML Data Attributes

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

<div id='strawberry-plant' data-fruit='12'></div>

In this example, strawberry plant has a custom data-* attribute that can be used with JS libraries. In order to read the attribute using plain old js: var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit');
// in jQuery
var $plant = $("#strawberry-plant");
var $fruitCount = $"fruit");
In order to set the attribute you can use: plant.setAttribute('data-fruit', '7');
// in jQuery
$'fruit', '7');

When not to use Data-*

Data Attributes are not meant to replace microformats in HTML. They are only meant to be used internally.

The presence/absence of a particular data attribute should not be used as a CSS hook for any styling. So you should not use data-attributes to change css from a certain element.

Dataset Property

The dataset property — part of the new HTML5 JavaScript APIs — will return a DOMStringMap object of all the selected element’s data-attributes. <div id='sunflower' data-leaves='47' data-plant-height='2.4m'></div> var sun = document.getElementById("sunflower");
sun.dataset.leaves // 47
Set to null by: sun.dataset.leaves = null;


Leave a Reply

Your email address will not be published. Required fields are marked *