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?
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.
The dataType option specifies the type of response data, in this case it is JSON. The timeout parameter specifies request timeout in milliseconds. We have also specified callback functions for error and success. The ajax() method returns an object of jQuery XMLHttpRequest.
Definition and Usage. The data() method attaches data to, or gets data from, selected elements. Tip: To remove data, use the removeData() method.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With