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

Possible duplicate:
jQuery Data vs Attr?

I am working on a project where I plan to store small amounts of data in the DOM. I specifically use it to attach a numeric value to a DOM element, which can be easily accessed elsewhere.

Is it better to insert a custom attribute like this:

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

Or use the jquery.data () function?

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

I know that both can be used, but I want to use the best practices, as well as choosing the most effective method. Is there a concrete advantage for one over the other, or perhaps another option for storing this small amount of data in the DOM?

+4
source share
1 answer

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

In addition, data() is likely to be faster due to the fact that it does not need to reference the DOM to install / receive, although I have not tested this.

+4
source

All Articles