1

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.

1 Answer 1

3

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah simply hash manipulation would take care of that, but for his stated intent this would work.
Cool @Zach, I will simply put "elem" in front of my data keys! And thank you for the documentation link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.