views:

215

answers:

2
+3  Q: 

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:

  • produce neat and valid HTML code
  • can store any type of data (objects, array,...) on elements

The main advantage of custom attributes are:

  • If WEB pages are not strict HTML, I can produce HTML code with custom attributes on the server
  • In firebug it's easy to inspect my HTML code in search of my custom attributes

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

+1  A: 

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.

mck89
+4  A: 

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.

geowa4