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)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
