Wednesday, November 24, 2010

How to store arbitrary data in the DOM using jQuery

Goal:

Storing arbitrary data inside the DOM

Issue:

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.

No comments:

Post a Comment