Wednesday, November 14, 2012

data(), attr() and prop() APIs

data(key, value) - Store arbitrary data associated with the matched elements.
Due to the way browsers interact with plugins and external code, the .data() method cannot be used on <object> (unless it's a Flash plugin), <applet> or <embed> elements. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

removeData() - Remove a previously-stored piece of data
As of jQuery 1.4.3, calling .removeData() will cause the value of the property being removed to revert to the value of the data attribute of the same name in the DOM, rather than being set to undefined. Removing data from jQuery's internal .data() cache does not effect any HTML5 data- attributes in a document

Data events: 
Besides of jQuery object, we can also use the data() on JavaScript objects, and handle 3 events
 setData
 getData
 changeData

Sample code:

var obj = {};
$(obj).data('name', 'jim');
console.log(obj);
$(obj).bind('setData', function (e, key, value) {
    console.log(key)
}).bind('getData', function (e, key, value) {
    console.log(key)
});
$(obj).data('age', 36);
$(obj).data('name');

attr(key) - Get the value of an attribute for the first element in the set of matched elements.
.attr() should not be used on plain objects, arrays, the window, or the document.
To retrieve and change DOM properties, use the .prop() method.

attr(key, value) - Set one or more attributes for the set of matched elements.

removeAttr() - Remove an attribute from each element in the set of matched elements.

prop(key) - Get the value of a property for the first element in the set of matched elements.

prop(key, value) - Set one or more properties for the set of matched elements.

removeProp() - Remove a property for the set of matched elements.
In general, it is only necessary to remove custom properties that have been set on an object, and not built-in (native) properties. Do not use this method to remove native properties such as checked, disabled, or selected. 
Use .prop() to set these properties to false instead.

Performance wise, prop() is much faster than attr() and data().

The confusing part is when to use each of these APIs. data() is to store arbitrary data in jQuery cache, and it also loads html5 data-attribute. attr() is for HTML attribute, while prop() is for DOM property. One of the reference articles gives a very good explanation the difference between attribute and property, and summarizes with below table. 

DOM Properties vs HTML Attributes
Standard DOM properties and attributes (like id, class/className, href, value etc) are synced, but the values are not always the same. For details, need refer to W3C specs.

Reference:



No comments:

Post a Comment