Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery data() vs attr(data)

Tags:

jquery

I would like to know the difference between saving data to an element using $(element).data({'foo' : 'bar'}) vs $(element).attr({ 'data-foo' : 'bar' }). And which of the two method would be best to use when saving a large amount of data in to an element? Thanks

like image 899
Johan Avatar asked Feb 25 '12 14:02

Johan


1 Answers

The $.data is used for storing information with respect to an element:

Docs:

Store arbitrary data associated with the specified element. Returns the value that was set.

On the other hand, attr is used to manipulate attributes of an element.

From your question, you seem to store the data, you should use $.data in that case.

data-* attributes are a feature of HTML5

Performance

.data() seems to be much more performance friendly according to this

I also find it cleaner since it's not visible for everyone in page source.

like image 154
Sarfraz Avatar answered Sep 22 '22 08:09

Sarfraz