Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any situation where I must use .attr() over .prop()?

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:

  • If I want to get the default state of a checkbox in the HTML, I can do $('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/)
  • Even though I often see .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().

like image 453
dallin Avatar asked Oct 19 '22 05:10

dallin


1 Answers

<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

like image 104
Shivakrishna Avatar answered Oct 21 '22 23:10

Shivakrishna