Featured Post

Jquery.prop()

.prop()
.prop(propertyName)
Get the value of a property for the first element in the set of matched elements.
.prop(propertyName, value)
Set one or more properties for the set of matched elements.
Returns: String
.prop(propertyName)
propertyName The name of the property to get.
Get the value of a property for the first element in the set of matched elements.
The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() only retrieves attributes.

For example, consider a DOM element defined by the HTML markup , and assume it is in a JavaScript variable named elem:

elem.checked true (Boolean)
$(elem).prop("checked") true (Boolean)
elem.getAttribute("checked") "checked" (String)
$(elem).attr("checked")(1.6+) "checked" (String)
$(elem).attr("checked")(pre-1.6) true (Boolean)
According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or an empty string value. The preferred cross-browser-compatible way to determine if a checkbox is checked is to check for a "truthy" value on the element's property using one of the following:

if ( elem.checked )
if ( $(elem).prop("checked") )
if ( $(elem).is(":checked") )
The code if ( $(elem).attr("checked") ), on the other hand, will retrieve the attribute, which does not change as the checkbox is checked and unchecked. It is meant only to store the default or initial value of the checked property.

Example Demo
Display the checked property and attribute of a checkbox as it changes.












Comments

Popular posts from this blog

[Inside AdSense] Understanding your eCPM (effective cost per thousand impress...