As far as I am aware, the .prop() function can do everything the .attr() function can do but in a generally safer and simpler way.
For example:
$('myCheckbox').prop('defaultChecked')
(instead of $('myCheckbox').attr('checked')
). This actually seems safer than using .attr('checked')
, as the attribute can lose it's value if the checkbox is dynamically changed, while .prop('defaultValue')
maintains the value (e.g. http://jsfiddle.net/p1Lrgwnb/1/)
.attr()
used consistently with values such as id
and name
on StackOverflow examples, .prop()
works fine with those as well. I am unaware of any reason .attr()
seems to be preferred for these values other than traditional conventions and habits.Is there ever a use case where I would need to use .attr()
or that the .prop()
function would not give me the information I needed?
EDIT: This question has nothing to do with what is the difference between .prop()
and .attr()
. I've studied those questions on StackOverflow in depth, including the one linked below (stackoverflow.com/questions/5874652/prop-vs-attr ). From my question, it is clear I understand fully the difference between the two, probably better than most. My question is are there any circumstances I must use .attr(), which is a completely different question from .prop() vs .attr().
<input id="check1" checked="checked" type="checkbox" />
.attr('checked') //returns checked
.prop('checked') //returns true
.is(':checked') //returns true
prop method returns Boolean value for checked, selected, disabled, readOnly..etc while attr returns defined string. So, you can directly use .prop(‘checked’) in if condition.
.attr() calls .prop() internally so .attr() method will be slightly slower than accessing them directly through .prop().
For jQuery 1.6+, prop will be mostly used because it is simple and wider than attr. In most old projects, attr is used to get current state information of element. But now prop has taken this job and attr would be replaced with prop.
Check this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With