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

  • Live Webinar Tuesday, August 26, 2014 1:00 PM EDT Customers are more empowered and connected than ever, and the customer's journey has grown more complex. Their expectations are growing and trust is diminishing as they may interact with multiple brands through web, mobile and social channels. Considering 70% of the buying process in a complex sale is already complete before prospects are willing to engage with a live salesperson -- it's critical to understand your customers and anticipate their needs.* …

  • Not long ago, security was viewed as one of the biggest obstacles to widespread adoption of cloud-based deployments for enterprise software solutions. However, the combination of advancing technology and an increasing variety of threats that companies must guard against is rapidly turning the tide. Cloud vendors typically offer a much higher level of data center and virtual system security than most organizations can or will build out on their own. Read this white paper to learn the five ways that cloud …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds