jQuery .attr() and .prop()

In jQuery, you have to be careful to use .attr() and .prop().

.attr() Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

.prop() Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

They are very similar, but not exactly same.

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 defaultSelectedshould 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.

More details see
http://api.jquery.com/attr/
and
http://api.jquery.com/prop/

Advertisements

About qianggan

Sr. Software Engineer
This entry was posted in Computers and Internet, Laravel, Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s