How to store arbitrary data in the DOM using jQuery


Storing arbitrary data inside the DOM


Storing data   : $('selector').attr('alt', 'my data');
Retrieving data: $('selector').attr('alt');

The ALT attribute is designed to be an alternative text description. For images the ALT text displays before the image is loaded. ALT is a required element for images and can only be used for image tags because its specific purpose is to describe images.So therefore, "alt" is an HTML attribute meant to give the tag meaning and not to store data. Also if you want to store the same data for different DOM objects than the data is duplicated for every DOM property found in the selector

The solution:

Storing data   : $('selector').data('key', 'my data');                  $('selector').data('key', function() { do something } ); 
Retrieving data: $('selector').data('key');

The data is not stored in the DOM, it is stored jQuery's reference to that object, so for each target found by the selector only a reference is stored and the data is stored once and referenced as many times as needed.

Print | posted @ Wednesday, November 24, 2010 9:27 AM

Comments on this entry:

No comments posted yet.

Post A Comment