Nov 06, 2011

jQuery .attr() vs .prop()

jQuery 1.6 introduces .prop() function and separates DOM Attributes and Properties, it raised a lot of questions about the difference between .attr and .prop functions. Before going jQuery, let us understand DOM Attributes and Properties. See following line


<input id="demo" type="text" value="TechBrij" />

Now, I changed text 'TechBrij' to 'jQuery' in textbox and see FireBug DOM Tab(select Show DOM Properties option in DOM tab dropdown)

 

firebug-dom-properties-attributes

You see Property "value" is 'jQuery', but Attribute "value" is still 'TechBrij'. Now you have got idea what it means. Only element's property is changed, because it is in the DOM and dynamic. But element's attribute is in HTML text and can not be changed. In wide sense, the property always represents the current state while the attribute (except in old versions of IE) represents the initial state or is meant for html attributes as they are strictly defined. the attribute tells you nothing about the current state.

In jQuery 1.6+, .prop() is used for property and .attr() for attribute. After changing text, when you run


$("#demo").attr("value");   // returns TechBrij
$("#demo").prop("value");   // returns jQuery

Points to Remember:

1. selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected..etc should be retrieved and set with the .prop() method. These do not have corresponding attributes and are only properties.

2. for a checkbox (jquery 1.6+)


<input id="check1" checked="checked" type="checkbox" />

.attr('checked') //returns  checked
.prop('checked') //returns  true
.is(':checked') //returns true

prop method returns Boolean value for checked, selected, disabled, readOnly..etc while attr returns defined string. So, you can directly use .prop('checked') in if condition.

3. .attr() calls .prop() internally so .attr() method will be slightly slower than accessing them directly through .prop().

Conclusion:

For jQuery 1.6+, prop will be mostly used because it is simple and wider than attr. In most old projects, attr is used to get current state information of element. But now prop has taken this job and attr would be replaced with prop.

Hope, It helps. Share your opinion in comment box.