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

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds