Your Search Results

    Using data-* attributes

    This article is in need of an editorial review.

    HTML5 is designed with extensibility for data that should be in the HTML, but not visible. data-* attributes allow us to store extra information on standard, semantic HTML elements without polluting the class name.

    HTML Syntax

    The syntax is easy. Say you have an article and you want to store some extra information that doesn’t have any visual representation. Just use data attributes for that:


    JavaScript Access

    Reading those out in JavaScript is also very simple. You could use getAttribute() to read them but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property:

    var article = document.querySelector('#electriccars'),
                  data = article.dataset;
    // data.columns -> "3"
    // data.indexnumber -> "12314"
    // data.parent -> "cars"

    Each property is a string (even if you omit the quotes in the HTML) and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute.

    CSS Access

    Now, as data attributes are plain HTML attributes you can even access them from CSS. For example to show the parent data on the article you can use generated content in CSS with the attr function:

    article::before {
      content: attr(data-parent);

    You can also use the attribute selectors in CSS to change styles according to the data:

      width: 400px;
      width: 600px;

    You can see all this working together in this JSBin example.

    Data attributes can also be stored to contain information that is constantly changing, like scores in a game. Using the CSS selectors and JavaScript access here this allows you to build some nifty effects without having to write your own display routines. See the following screencast for an example using generated content and CSS transitions:

    The code example shown in the screencast is also on JSBin.


    Do not store content that should be visible and accessible in data attributes, because assistive technology may not access them. In addition, search crawlers do not index data attributes' values.

    Sadly enough it seems there is nothing that is so simple and useful that doesn’t come with a price. In this case the main issues to consider are Internet Explorer support and performance. Internet Explorer 11+ provides support for the standard, but all earlier versions do not support dataset. To support IE 10 and under you need to access data attributes with getAttribute()  instead. Also, the performance of reading data-attributes compared to storing this data in a JS data warehouse is bad. Using dataset is even slower than reading the data out with getAttribute().

    That said, though, for content that is not to be shown they are a great solution.

    See also

    Document Tags and Contributors

    Last updated by: andrew.carpenter,