What is the difference between .prop() and .attr() in jQuery?
Quick Answer
.attr() reads/writes the HTML attribute — the initial value in the markup. .prop() reads/writes the live DOM property — the current state. For things like checked, selected, disabled and value, use .prop(); the attribute only reflects the default.
.attr() deals with the HTML attribute — basically what's written in the markup, the initial value. .prop() deals with the current DOM property, the live state. The classic example is a checkbox: after the user clicks it, .attr('checked') still reflects the original markup, but .prop('checked') gives you the real current true/false. So for checked, selected, disabled and value I use .prop(). This was cleaned up in jQuery 1.6 — before that .attr() tried to be both and was unreliable.
$(':checkbox').attr('checked')→ returns the original"checked"orundefined, regardless of what the user clicked.$(':checkbox').prop('checked')→ returns the current boolean state.- Setting:
.prop('disabled', true)works;.attr('disabled', true)can be inconsistent across versions. - Custom
data-*attributes: use.attr('data-x')or.data('x')(jQuery's data cache — note it type-casts and doesn't write back to the DOM). - This split was introduced in jQuery 1.6; before that
.attr()tried to do both and was buggy.