Use jQuery's data() method to store data in the DOMUse 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:

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.

Comments

blog comments powered by Disqus