Have you ever found yourself using element
class names or
Wow, that's a great idea! I implore you to rid your mind of that thought immediately and continue reading.
Thanks to HTML5, we now have the ability to embed custom data attributes on all HTML elements. These new custom data attributes consist of two parts:
- Attribute Name
- The data attribute name must be at least one character long and must be prefixed with '
data-'. It should not contain any uppercase letters.
- Attribute Value
- The attribute value can be any string.
Using this syntax, we can add application data to our markup as shown below:
<ul id="vegetable-seeds"> <li data-spacing="10cm" data-sowing-time="March to June">Carrots</li> <li data-spacing="30cm" data-sowing-time="February to March">Celery</li> <li data-spacing="3cm" data-sowing-time="March to September">Radishes</li> </ul>
data- attributes we’ve added to our
<li> elements, we can now display this information instantly without having to worry about making any Ajax calls and without having to make any server-side database queries.
Prefixing the custom attributes with
data- ensures that they will be completely ignored by the user agent. As far as the browser and indeed the website’s end user are concerned, this data does not exist.
The spec says (emphasis ours):
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.
These attributes are not intended for use by software that is independent of the site that uses the attributes.
Every HTML element may have any number of custom data attributes specified, with any value.W3C Specification
How can I use data attributes?
As custom data attributes are valid HTML5, they can be used in any browser that supports HTML5 doctypes. Thankfully, this is pretty much all of them. In addition to aiding backwards compatibility, this also ensures that custom data attributes will remain a scalable, cross-platform solution well into the future.
Now that we have a broad understanding of what data attributes are, let's take a look at how they can be used:
- To store custom web analytics tagging data as demonstrated by Jason Karns
<video>subtitles as demonstrated by Bruce Lawson
What shouldn’t I use data attributes for?
Although flexible, data attributes aren’t an appropriate solution for all problems.
- Data attributes should not be used if there is a existing attribute or element which is more appropriate for storing your data. For example, date/time data should probably be presented semantically in a time element instead rather than stored in custom data attributes.
- Custom data attributes are not intended to compete with microformats. It is clearly stated in the spec that the data is not intended to be publicly usable. External software should not interact with it. Marking up contact details or event details using custom data attributes would be wrong, unless of course it is only intended to be used by your own internal scripts.
- The presence/absence of a particular data attribute should not be used as a CSS hook for any styling. Doing so would suggest that the data you are storing is of immediate importance to the user and should be marked up in a more semantic and accessible manner.
Now that we understand what custom
setAttribute methods as shown below:
<div id='strawberry-plant' data-fruit='12'></div> <script> // 'Getting' data-attributes using getAttribute var plant = document.getElementById('strawberry-plant'); var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12' // 'Setting' data-attributes using setAttribute plant.setAttribute('data-fruit','7'); // Pesky birds </script>
This method will work in all modern browsers, but it is not how
data- attributes are intended to be used. The second (new and improved) way to achieve the same thing is by accessing an element’s
dataset property. This
DOMStringMap object of all the selected element's
data- attributes. When using this approach, rather than using the full attribute name, you can ditch the
data- prefix and refer to the custom data directly using the name you have assigned to it. Data attribute names which contain hyphens will be stripped of their hyphens and converted to CamelCase.
<div id='sunflower' data-leaves='47' data-plant-height='2.4m'></div> <script> // 'Getting' data-attributes using dataset var plant = document.getElementById('sunflower'); var leaves = plant.dataset.leaves; // leaves = 47; // 'Setting' data-attributes using dataset var tallness = plant.dataset.plantHeight; // 'plant-height' -> 'plantHeight' plant.dataset.plantHeight = '3.6m'; // Cracking fertiliser </script>
If, at some point in your script, a specific
data- attribute becomes redundant and is no longer needed, it is also possible to completely remove that attribute from the DOM element by setting it to a value of
plant.dataset.leaves = null; // Caterpillars attack!
Unfortunately, the new
dataset property has not yet been implemented in any browser, so in the meantime it’s best to use
setAttribute as demonstrated earlier.
While developing your application, you may find it useful to be able to select elements based on the presence of — or indeed the specific values of — their custom
data- attributes. This can be achieved quickly and easily using
querySelectorAll as shown below:
// Select all elements with a 'data-flowering' attribute document.querySelectorAll('[data-flowering]'); // Select all elements with red leaves document.querySelectorAll('[data-foliage-colour="red"]');
A word of warning
As data attributes become more widely used, the potential for clashes in naming conventions becomes much greater. If you use an unimaginative attribute name such as
data-height, then it is likely you will eventually come across a library or plugin that uses the same attribute name. Multiple scripts getting and setting a common
data- attribute will probably cause chaos. In order to avoid this, I encourage people to choose a standard string (perhaps the site/plugin name) to prefix all their
data- attributes — e.g.
setAttribute safe in the knowledge that they will work in all major browsers.
If you’re super keen to have a play with the new
dataset property but disappointed that it hasn’t been implemented, fear not!, for there is a light at the end of the tunnel. You might be interested in looking at Dr Remy’s experimental code, which partially enables the
dataset functionality in some browsers by editing the
The code supports the retrieval of
dataset property would. Although this code is mainly a proof of concept, it may be useful for mobile application or intranet development in closed environments where cross-browser (IE) compatibility is not an issue.