Use jQuery's data() method to store data in the DOM
Posted July 7th, 2009 in Javascript
jQuery has a .data() method for storing data in the DOM should you need to for one reason or other. This is preferable to storing data in some other attribute such as "rel" or "alt" which is often seen in tutorials and examples on blogs.
For example if you had a elements with the id "foo" and "bar" you could set data with a name of "fruit" to "orange" for #foo and "banana" for #bar like so:
$('#foo').data('fruit', 'apple');
$('#bar').data('fruit', 'banana');
To fetch the value at a later time call the .data() method just passing in the name like so, where the value is displayed in an alert dialog:
alert( $('#foo').data('fruit') );
If you don't want to assign the data to a particular element you could always assign it to the body instead:
$('body').data('fruit', 'orange');
alert( $('body').data('fruit') );
Related posts:
- Accessing form elements by name with jQuery (Tuesday, June 23rd 2009)
- Loop through selected elements with jQuery (Revised) (Tuesday, April 14th 2009)
- How to tell if an element exists with jQuery (Friday, April 10th 2009)
- Get the total number of matched elements with jQuery (Tuesday, March 31st 2009)
- Attaching an event to an element with jQuery (Tuesday, February 24th 2009)
- Dynamically get and set an elements content with jQuery (Sunday, January 11th 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

