Search code examples
javascriptjqueryhtmldomjquery-data

Storing Data in the DOM - Custom Attributes or .data()


Possible Duplicate:
jQuery Data vs Attr?

I'm working on a project where I plan on storing small amounts of data in the DOM. I'm specifically using it to attach a numerical value to a DOM element to be easily accessed elsewhere.

Is it better to insert a custom attribute like so:

 $('#storeThingsHere').attr('data-count', superArray.length);

Or to utilize jquery's .data() function?

 $('#storeThingsHere').data("count", superArray.length);

I know both can be used, but I want to utilize best practices while also choosing the most efficient method possible. Is there a particular benefit to one over the other, or possibly another better option to store this small amount of data in the DOM?


Solution

  • Use data. Any type can be stored using data as jQuery uses an internal object to store them, whereas only strings can be stored using attr.

    Also, data() will most likely be faster due to it not having to reference the DOM for setting/getting, although I've not tested this.