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

  • It's often said that data is the lifeblood of many businesses, yet many organizations continue to struggle with keeping their data safe -- safe from system crashes, human error, and natural disasters. There are two major factors preventing most businesses from adequately protecting their data: complexity and inefficiency. The combination of complexity and inefficiency leads to increased risk for the organization. It means more software licenses are required, specific skillsets are needed from employees, and …

  • The 2014 State of DevOps Report — based on a survey of 9,200+ people in IT operations, software development and technology management roles in 110 countries — reveals: Companies with high-performing IT organizations are twice as likely to exceed their profitability, market share and productivity goals. IT performance improves with DevOps maturity, and strongly correlates with well-known DevOps practices. Job satisfaction is the No. 1 predictor of performance against organizational …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date