Pier Luigi
Pier Luigi

Reputation: 7871

Use of jQuery.data

Well, I admit: I've extensively used jQuery.attr to store custom data in DOM elements in many, many scripts. I'm wondering if convert all my script to use jQuery.data instead of jQuery.attr. As far as I understand, the advantages of jQuery.data are:

The main advantage of custom attributes are:

Can someone tell me if I miss something or if exists issues that makes use of jQuery.data highly preferable?

Upvotes: 6

Views: 871

Answers (2)

geowa4
geowa4

Reputation: 41813

You pretty much got it. But do you know every HTML attribute? There are a lot of attributes that are used by screen-readers and other usability tools that are not standard (yet). What happens when you accidentally use the role attribute and a screen-reader picks that up? Using $.data isn't only neater, it's safer for you and makes more sense.

EDIT: I learned something last night that is pertinent to this question. In HTML5, you ca specify custom attributes for storing data. These custom attributes must be specified using the prefix "data-". See the spec for more detailed information.

What this means, is that you do not have to go back and change all of your old code, because you will never have to worry about overlapping with other attributes if you prefix with "data-". However, if you need to store more complicated data types than strings, use $.data.

Upvotes: 5

mck89
mck89

Reputation: 19231

I think that you don't miss anything but storing data on dom elements attributes is always a bad practice so i think you should use the $.data function.

Upvotes: 1

Related Questions