jQuery Support for HTML5 Data Attributes

As HTML 5 has become more popular among web developers recently, another popular web client framework jQuery is also proving to be up to date in providing its support for HTML 5. In this article I will be discussing the data attribute features of HTML 5 and the support offered by jQuery with a few examples.

HTML 5 Data Attributes

HTML 5 provides a good feature called the custom data attributes where you can store the data at the page level and can access it from the client scripts as and when it is needed. Developers who have done a few workarounds in the past for storing the data will be relieved. All you need to do is add the prefix “data-“ to the custom attribute of the HTML control and get it working. Below is a sample HTML code.

<body>
    <div data-site="www.codeguru.com" data-category="Technology">Hi, Welcome to HTML 5 data attributes!</div>
<div data-name="Dave" data-age=23 data-dept="Clerical">Hi Dave!</div>
</body>
</html>
 

The beautiful thing with the custom data attributes is that it is backward compatible and it does not have browser dependency issues.

.data() in jQuery API

Nowadays most of the web applications use jQuery, so for developers to make use of HTML 5 features like custom data attributes, it is important that they also have adequate support from jQuery to accomplish the tasks effectively. jQuery provides full support for the HTML 5 custom data attributes. The .data() method of jQuery API is used to play with the HTML 5 custom data attributes.

In the following sections let us see the basic operations set, get and remove what you can do with JQuery on HTML custom data attributes.

Setting Data Attribute Values Using jQuery

In this section let us see about setting the data attribute value through jQuery.

<!DOCTYPE html>
<html>
<head>
    <title>Untitled Page</title>
    <script type="text/javascript">
        $("#btnSet").click(function (e) {
            $("#divEmployee").data("name", "Dave");
            $("#divEmployee").data("age", "23");
            $("#divEmployee").data("dept", "Clerical");
        });
    </script>
</head>
<body>
    <div id="divEmployee">Hi Dave!</div>
    <input type="button" id="btnSet" value="Set Value"/>
</body>
</html>
 

You can also pass a data object as a whole to the .data function, as shown in the below example, instead of writing repeated code.

    <script type="text/javascript">
        $("#btnSet").click(function (e) {
            $("#divEmployee").data({ "name": "Dave", "age": 23, "dept": "Clerical" });
        });
    </script>
 

The same also can be written as:

    <script type="text/javascript">
        $("#btnSet").click(function (e) {
            $("#divEmployee").data("name", "age", "dept").data("Dave", 23, "Clerical");
        });
    </script>

Fetching Data Attribute Values Using jQuery

In this section we will see how to fetch the data attribute values from the HTML controls using jQuery. Below is the sample.

<!DOCTYPE html>
<html>
<head>
    <title>Untitled Page</title>
    <script type="text/javascript">
        $("#btnSet").click(function (e) {
            var name = $("#divEmployee").data("name")
            var age = $("#divEmployee").data("age")
            var dept = $("#divEmployee").data("dept")
        });
    </script>
</head>
<body>
    <div data-name="Dave" data-age="23" data-dept="Clerical" id="divEmployee">Hi Dave!</div>
    <input type="button" id="btnGet" value="Get Value"/>
</body>
</html>
 

If the data attribute of the HTML control has the value as a data object itself then the individual property values can be accessed as shown below.

<!DOCTYPE html>
<html>
<head>
    <title>Untitled Page</title>
    <script type="text/javascript">
        $("#btnSet").click(function (e) {
            var name = $("#divEmployee").data("employee").name;
            var age = $("#divEmployee").data("employee").age;
            var dept = $("#divEmployee").data("employee").dept;
        });
    </script>
</head>
<body>
    <div data-employee='{"name":"Dave", "age": 23, "dept":"Clerical"}' id="divEmployee">Hi Dave!</div>
    <input type="button" id="btnGet" value="Get Value"/>
</body>
</html>
 

Removing Data Attributes Using jQuery

Finally in this section let us see how to remove a data attribute from an HTML control using jQuery API.

<!DOCTYPE html>
<html>
<head>
    <title>Untitled Page</title>
    <script type="text/javascript">
        $("#btnSet").click(function (e) {
            $("#divEmployee").removeData("employee");
        });
    </script>
</head>
<body>
    <div data-employee='{"name":"Dave", "age": 23, "dept":"Clerical"}' id="divEmployee">Hi Dave!</div>
    <input type="button" id="btnGet" value="Get Value"/>
</body>
</html>
 

I hope this article was helpful in understanding the different operations that you can perform on data attributes using jQuery.

Happy reading!



Related Articles

Comments

  • dev

    Posted by phasthal on 06/21/2012 04:25am

    Thanks Arun, It is really excellent. One thing is not clear is, what is the expected output and purpose of "removeData()"? I just added the below statement after removeData()as below: $("#divEmployee").removeData("employee"); var name = $("#divEmployee").data("employee").name; console.log("name="+name); // prints the name; Dave Thanks, phasthal

    • reply

      Posted by V. N. S. Arun on 07/18/2012 10:16pm

      Example for removeData was not correct. removeData() would remove only the data added using $("#divEmployee").data("employee") = 'some value', but in the example I have hard coded the data-employee on the DIV control. Please check and let me know if it has clarified your question.

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • Recently, Forrester Consulting conducted a Total Economic Impact™ (TEI) study to better understand the impact of incorporating Polycom voice solutions with Microsoft Lync. Forrester interviewed a company that had already deployed the Lync/Polycom combination to determine its potential return on investment (ROI). Microsoft Lync provides presence information and promotes voice and video collaboration. Polycom extends the benefits of Lync with voice endpoints and further enables collaboration in multiple …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds