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() retrieves attributes.
For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument,defaultChecked, and defaultSelected should be retrieved and set with the .prop()method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.
Concerning boolean attributes, consider a DOM element defined by the HTML markup <input type="checkbox" checked="checked" />, and assume it is in a JavaScript variable namedelem:
elem.checked | true (Boolean) Will change with checkbox state |
|---|---|
$(elem).prop("checked") | true (Boolean) Will change with checkbox state |
elem.getAttribute("checked") | "checked" (String) Initial state of the checkbox; does not change |
$(elem).attr("checked")(1.6) | "checked" (String) Initial state of the checkbox; does not change |
$(elem).attr("checked")(1.6.1+) | "checked" (String) Will change with checkbox state |
$(elem).attr("checked")(pre-1.6) | true (Boolean) Changed with checkbox state |
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") )