Difference between jQuery attr() and prop()

By Nethru Limited (www.nethru.com)

jQuery

Starting from jQuery 1.6, they introduced the method prop(). According to the official document of jQuery, the reason they introduced this new method is due to inconsistent behavior when using attr() before jQuery 1.6.

Before jQuery 1.6, the attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior.

Someone may ask when we have to use attr() and when to use prop(), this is how the official document said.

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

That means they suggest us to use prop() when we are going to get the attributes when boolean result, like checked, disabled or selected.

Starting from jQuery 1.9.0, jQuery does not recommend to use attr() to get any boolean attributes any more. If we use attr() to get checked attribute, jQuery will return undefined.

$(function() {
    $('input').click(function() {
        console.log($(this).attr('checked'));
    });
});
// In jQuery 1.8.3 or before, checked => "checked", not checked => undefined
// In jQuery 1.9.0 or after, checked => undefined, not checked => undefined

To fix this issue, just following jQuery’s recommendation to use prop() to get boolean attributes.
Finally, this is list showing when to use attr() and when to use prop(), hope that it is useful for you.

Attribute attr() prop()
accesskey
align
async
autofocus
checked
class
contenteditable
draggable
href
id
label
location
multiple
readOnly
rel
selected
src
tabindex
title
type
width

2 comments

Leave a Reply

Your email address will not be published. Required fields are marked *