4

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?

Community
  • 1
  • 1
streetlight
  • 5,968
  • 13
  • 62
  • 101
  • I believe the difference is that the `data` method will often store the data internal as opposed to directly in the DOM. I prefer using `attr` just so I can inspect the DOM easily and see the data values. Please correct me if my understanding of the methods is wrong however. – Darren Coxall Jan 08 '13 at 15:50
  • 1
    Good question, I've often wondered the same thing. I tend to use data-attributes but I'd be interested in knowing which is better. – Syon Jan 08 '13 at 15:51
  • i had the same thoughts as freakyDaz, but the point why i barely use it is that you cant read already set data attributes with it, when they arent made from jquery itself. – b1nary Jan 08 '13 at 15:54

1 Answers1

4

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339