Use jQuery's data() method to store data in the DOM

Posted 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:


Comments