So for a while I have always been under the impression, that for 99.9% of the time that you would need to change the value of a DOM elements attribute, either of these methods would work and that both work the same. I found out after banging my head against the wall for several hours that I was very much wrong.
What JQuery API says
Before I dive into what the differences are, lets loo at the JQuery API. Here is what it says for each:
.attr() Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
.prop() Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.
Ok, so far the definitions are identical. That would on fist impression say that my assumptions were correct. Lets keep looking shall me!
Half way down the page on the .attr() method, there is an update in the API that states in 1.6 DOM / JQuery properties (like ‘checked’, ‘selected’ and ‘disabled’) are more reliably found using .prop(). This means that going forward, although attr() is not deprecated, it would probably be best to get used to just using .prop() instead of guessing what will work. This would have been good to now about and is shows exactly the reason we as the leaders in technology must stay on top of new technologies AS WELL AS technologies that already exist. There are patches and deprecations all the time that need to be taken into account from all angles. Debugging, Architecture and Development all require us to stay on our toes when it comes to updates and new releases of toolsets we use.
One Last Thing
An example of this confusion lies with a property of ‘disabled’. This can be set in a few ways, but before 1.6, you were able to use the attr() method instead of prop(). When you used attr(), your code would loo something like:
$( "checkbox" ).attr( "checked", "checked" ) );
This would set the checbox with that Id to “checked”. So the checkbox would show on the screen show. This no longer work consistently.
Now, if you were to use the prop() method using the same technique, it would fail. The right way to use this is the following:
$( "checkbox" ).prop( "checked", true ) );
This will do the same as the above used to. You will notice that the prop method required the Boolean instead of the word. This is because instead of just tacking on the string value of ‘checked’ it is actually validating the data provided as of type Boolean.
Another day of learning and migraines