Last Updated: November 30, 2021
·
7.979K
· abishekrsrikaanth

Data Attributes in HTML 5

Back in the days of HTML4/XHTML, the usage of the rel and the class attributes on the DOM were quite extensive for DOM selection and arbitary data storage on the browser.

For example, If an list item needs to indicate the user who had 7 notification messages, we sometimes used the class attributes to store the data for the user as mentioned below. This is how some practiced and others had different other ways.

<li class="item user_john message_notify_7"></li>

With the invent of HTML 5, the HTML and Javascript programming has become so flexible, easy and developer friendly and thanks to it, we can not store artibitary data using the data attributes that it provides.

Data Attributes

data-* attributes allow us to store extra information on standard, semantic HTML elements without polluting the class name.

The syntax for data attributes is quite easy. We can define data attributes for the above example as :

<li class="item" data-user="john" data-message-notify="7"></li>

Isn't this cleaner that what we did previously. The specification for custom data attributes states that any attribute that starts with “data-” will be treated as a storage area for private data. This allows us to maintain cleaner HTML code and also store some extra information that doesn't have any visual representation.

Javascript Accessor

Javascript allows us to access this information easily using the dataset property that returns a DOMStringMap.

Lets us look at a simple example that allows us to retrieve all the data attributes from the above example. I am going to add an id attributes so that it is easy to understand the initial example.

<li id='itemJohn' class="item" data-user="john" data-message-notify="7"></li>
var item = document.getElementById('itemJohn');
var custom_attributes = item.dataset;

//-> data-user="john"
//-> data-message-notify="7"

JQuery Accessor

JQuery provides the data() method that returns a String Map of all the data attributes set on a particular DOM object. Let us take an example of how to retrieve the custom attributes using JQuery.

var custom_attributes = $('#item').data();
//returns -> { user:john, message-notify:7}

The data() additionally take 2 optional parameters that helps in specific selection of the attributes and the store values.

Getting values

var user_notifications = $('#userJohn').data('message-notify');
//returns -> 7

Setting Values

$('#userJohn').data('message-notify',10);

The above example will update the data attributes message-notify from 7 to 10.

If a particular data attribute is not present when setting the value, a new one is automatically created and added to the dataset of the DOM Element.

Searching DOM using data attributes.

The JQuery selectors helps us to search a list of custom data attributes using the keys of data attributes. Let us for example say we have a list of LI with various data attributes as shown below.

<ul>
    <li data-user="john" data-friends="4" data-admin="YES"></li>
    <li data-user="doe" data-friends="5" data-admin="NO"></li>
    <li data-user="jessy" data-friends="6" data-admin="YES"></li>
    <li data-user="michael" data-friends="7" data-admin="NO"></li>
    <li data-user="jane" data-friends="1" data-admin="YES"></li>
    <li data-user="george" data-friends="14" data-admin="NO"></li>
</ul>

The jquery selector can be used to get all the objects that use the custom data attribute data-user. To do this, we use:

var users = $('[data-user]');

This will return a list of li objects that have the custom attribute data-user. You can now access all the users by looping through the users variable.

$.each(users,function(idx,item){
    var isAdmin = $(item).data('admin');
    var friends_count = $(item).data('friends');
    $(item).data('notifications','4');
});

If you wanted a list of all the users who are admin, then:

var admin_users = $('[data-admin="YES"]');

This will return the li objects with data-user belonging to JOHN|JESSY|JANE

You can create a helper method to search dynamically

function fetchByAdminType($type){
    return $('[data-admin="' + $type + '")]');
}

var admin_users = fetchByAdminType('YES');
var non_admin_users = fetchByAdminType('NO');

CSS Accessor

Since data attributes are plain HTML attributes, you can access them using CSS as well. Let us for example want to have a specific font coloring for all the users who belong to Admin type, we can do it using:

li[data-admin="YES"] {
  color: '#bbb';
  background: '#555';
  font-weight: 'bold';
}

Christian Heilmann shows more ways on how to use data attributes in this screencast.

The datalist API is supported by all modern browsers but not IE10 and below. A shim is available but it’s possibly more practical to use jQuery if you’re coding for the older browsers.