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
Asked
Active
Viewed 3,493 times
2 Answers
9
The $.data
is used for storing information with respect to an element:
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.

Maher Fattouh
- 1,742
- 16
- 24

Sarfraz
- 377,238
- 77
- 533
- 578
-
Im saving an object using JSON.stringify. The data() method can be used to fetch html5 data attributes saved using the .attr() as well. But i suppose using data() would be better. When using `data`, where is it stored? It doesnt show up as a data attribute on the element – Johan Feb 25 '12 at 14:15
-
@Johan: With `$.data` attribs won't be added to element since it is not for attributes but data. As for storing, I believe jQuery stores it internally in some object. – Sarfraz Feb 25 '12 at 14:19
-
Ok, thanks for the info. Do you know if IE7 has any problem with data()? – Johan Feb 25 '12 at 14:23
-
@Johan: I haven't worked using it with IE7 but you can try it out. I think since jQuery does work for browsers till IE6, it should work fine. – Sarfraz Feb 25 '12 at 14:24
1
I would say data, because that is what it was meant to do. It supports the exact type of functionality you are trying to implement. http://api.jquery.com/jQuery.data/

thescientist
- 2,906
- 1
- 20
- 15