DOM Attributes and Properties treatment with jQuery 1.6 by Ivo Stoykov
jQuery 1.6 introduces .prop() and .removeProp() methods which allow modifying or removing a DOM property.
.prop()
method get a property value of the first found element and returns it as a string. If required property has not been set or searched element has not been found returned values will be undefined .
Earlier jQuery versions used to get the value of a property or attribute the .attr() method. Version 1.6 differentiate both attributes and properties supplying method for each of them. For instance .attr(“checked”) of an input type=”checkbox” element will return “checked” or empty string (“”) rather than true/false (as is the case is previous versions).
The preferred way to determine if a checkbox is checked (in cross-browser-compatible way) one of the following might be used:
if ( el.checked )
if ( $(el).prop("checked") )
if ( $(el).is(":checked") )
.attr(“checked”) will retrieve the attribute, which does not change but stores the default or initial value of the checked property. Here is a short snippet demonstrating this behavior:
.prop() accept an string input parameter identifying property to get. In this case method returns a string representing property value.
As a second parameter a value (or function returning desired value) to set is applicable. If function is used within it, the keyword this refers to the current element.
.prop() should be used instead of the .attr() to set disabled and checked values. The .val() method should be used for getting and setting value.
.removeProp()
Properties set by the .prop() method could be removed by .removeProp() method. The method accept two parameters:
propertyName The name of the property to set.
value A value to set for the property.
Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element.
Instead set these properties to false using .prop().
This is a nice new feature added to jQuery 1.6 which make coding even more intuitive and easy. It also complies with the W3C forms specification where the boolean attribute as checked attribute is, meaning that property is true if the attribute is present at all, nevertheless it might have empty string or no value at all.
Comments (0)