jQuery loop through data() object

bart picture bart · Apr 21, 2009 · Viewed 38.5k times · Source

Is it possible to loop through a data() object?

Suppose this is my code:

$('#mydiv').data('bar','lorem');  
$('#mydiv').data('foo','ipsum');  
$('#mydiv').data('cam','dolores');

How do I loop through this? Can each() be used for this?

Answer

John Strickler picture John Strickler · Jun 1, 2010
$.each($.data(this), function(i, e) {
   alert('name='+ i + ' value=' +e);
});

This will iterate through each property in 'this' element's data object.