Home arrow JavaScript arrow jQuery`s data() Method
JAVASCRIPT

jQuery`s data() Method


In this programming tutorial, you will learn how to use the jQuery data() method to store, retrieve, and manipulate data.

Author Info:
By: Alejandro Gervasio
Rating: 2 stars2 stars2 stars2 stars2 stars / 1
June 06, 2011
TABLE OF CONTENTS:
  1. · jQuery`s data() Method
  2. · Storing Data in Multiple HTML Nodes

print this article
SEARCH DEVARTICLES

jQuery`s data() Method
(Page 1 of 2 )

By far the most popular JavaScript framework available nowadays, it seems that there’s nothing left to discover when it comes to the abilities that jQuery encapsulates behind its API.

If you’re anything like me, you probably think that you know everything about jQuery and that its bunch of methods have nothing new to offer. Well, as I just before, don’t walk the path of early assumptions, as asides from the capabilities that you know so well, the library includes an underused method, called “data()”, which permits you to store and retrieve data from several HTML nodes with extreme ease.

Don’t let the simplicity of the “data()” method fool you; when used in a clever way it can be of great help, especially when it comes to manipulating data that does not need to be persisted between different requests. Moreover, the method acts like a global registry mechanism that can be accessed from different places in the DOM, which allows you to attach data (integers, strings and even complex JSON objects) to an HTML element and retrieve it later on for further processing.

Getting started: developing an introductory example

As noted in the introduction, the “data()” method behaves like a registry where it’s possible to save and fetch data by means of literal keys, very similar to what can be done with many programming languages today. Having said that, the first example that I plan to create in order to demonstrate the method’s functionality will consist of saving the index value of a simple link in this registry when clicking on it.

If my previous explanation sounds somewhat confusing to you, take a close look at the following code sample, which will make your doubts vanish in a snap. Here it is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example storing data with the 'data()' method</title>
<script type="text/javascript" src="
https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    // store the index value of the clicked element with the 'data()' method
    $("#main a").click(function() {
        var index = $("#main a").index(this);
        $(this).data('index', index);
        $('#data').html('The value stored in the clicked element is ' + index + '.');
    });
});
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #eee;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
h2 {
    padding-bottom: 10px;
    margin: 0 0 30px 0;
    font-size: 3em;
    color: #585858;
}
/* main wrapper */
#wrapper {
    width: 650px;
    margin: 0 auto;
    background: #fff;
}
/* main sections */
#header, #main, #footer {
    padding: 20px;
}
/* storage list */
#main ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
    overflow: auto;
}
#main ul li a {
    color: #00f;
}
/* data container */
#data {
    padding: 20px;
    text-align: center;
    color: #f00;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h2>Header section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
    <div id="main">
        <h2>Example storing data with the 'data()' method</h2>
        <ul>
            <li><a href="#">Save the index of the target node...</a></li>
        </ul>
        <div id="data"></div>
    </div>
    <div id="footer">
        <h2>Footer section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
</div>
</body>
</html>

As the above example shows, the use of the “data()” method is a breeze to grasp. In this particular case, the index value of a trivial link is firstly stored in the registry with a key “index” assigned to it, and lastly displayed within a generic container, identified as “data” as well.

The result of this storage process can be seen more clearly in the following image. Check it out:

See how simple it is to attach a given value to an HTML element with “data()”? However, I’m only scratching the surface when it comes to exploring the functionality provided by the method, as it allows you to attach and save data to multiple HTML nodes.

In the next section I’ll be extending the previous example, which this time will use the method for saving the index value of several links.


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials