Reputation: 319
I have many div elements that in turn have many data attributes.
For each element I want to build an array containing the names and values of the data attributes.
My code looks like this:-
$( "#"+progWindowID ".newItem" ).each( function() {
var itemData = {
elemCategory : $(this).attr( 'data-Category' ),
elemType : $(this).attr( 'data-Type' ),
elemName : $(this).attr( 'data-Name' ),
elemTop : $(this).attr( 'data-Top' ),
elemLeft : $(this).attr( 'data-Left' ),
elemHeight : $(this).attr( 'data-Height' ),
elemWidth : $(this).attr( 'data-Width' ),
elemCreatedBy : $(this).attr( 'data-CreatedBy' ),
elemCreatedOn : $(this).attr( 'data-CreatedOn' )
};
}
Can I loop through the data attributes to build the array using each data attribute's name as a key in the array? Then when I add more data attributes later my code will still work.
Upvotes: 1
Views: 1070
Reputation: 1941
Just do $(obj).data();
it will give you a hash of the properties.
Example:
$( "#"+progWindowID ".newItem" ).each( function() {
var itemData = $(this).data();
});
jQuery documentation: http://api.jquery.com/data/
Upvotes: 3