Block Chain - .prop() and .attr()?
In jQuery, .prop()
and .attr()
are both used to get or set values on HTML elements, but they behave differently because they target different kinds of properties.
1. .attr()
— Attribute
-
Purpose: Works with HTML attributes, the values defined in the HTML markup.
-
Examples of attributes:
id
,href
,src
,class
,title
,disabled
,checked
. -
Behavior:
-
Gets or sets the original HTML attribute.
-
The value may not reflect the current state if the property changes dynamically in the DOM.
-
<input type="checkbox" id="check" checked>
// Using .attr()
console.log($('#check').attr('checked')); // "checked" (as per HTML)
$('#check').attr('checked', false); // Removes checked attribute in HTML
2. .prop()
— Property
-
Purpose: Works with DOM properties, the actual current state of the element in the browser.
-
Examples of properties:
checked
,selected
,disabled
,value
. -
Behavior:
-
Reflects the current state of the element, not just the HTML markup.
-
Useful for checkboxes, radios, and other dynamic elements.
-
// Using .prop()
console.log($('#check').prop('checked')); // true or false (current state)
$('#check').prop('checked', false); // Unchecks the checkbox
Key Differences
Feature | .attr() |
.prop() |
---|---|---|
Works on | HTML attributes | DOM properties |
Returns | Original attribute value | Current property value |
Common use | href , id , title |
checked , selected , disabled |
Changes reflect | Markup only | Actual DOM state |
Rule of thumb:
-
Use
.attr()
for static attributes you set in HTML. -
Use
.prop()
for dynamic properties like checkboxes, radios, or disabled states.