5 ms·
If I understand correctly, .prop reflects the current state of the DOM, .attr reflects the state when loaded or last updated with javascript. If you have:
by morrow 15y ago
If I understand correctly, .prop reflects the current state of the DOM, .attr reflects the state when loaded or last updated with javascript.
If you have:
<input id="test" type="text" value="initial" />
On load, the page should show for $("#test")
.prop("value") = "initial",
.attr("value") = "initial"
Then, if you type in "current" into the 'test' input box, the page should show:
.prop("value") = "current",
.attr("value") = "initial"
without any other events taking place that would update the value.
- ThePinion 15y agoThank you! The pure definition of simpler terms I was looking for. Going through my code now to see if I need to make changes!
- mcrittenden 15y agoNote that in the above example, one should really be using .val() instead of .attr('value'), and if so, then nothing will need to be changed.
- pak 15y agoQuestion: When would you ever want the .attr("value")=="initial" in real code? How often is it that you want the original value encoded in the HTML as opposed to the current value of the element as entered by the user? This is part of why I think .prop vs .attr is a regression. It makes me think twice before I use either--even if this is closer to how the DOM actually behaves, the point of jQuery used to be that it could hide those inane details from me.
- timdown 15y agoThe difference between attributes and properties is not an inane detail. It's fundamental, and if you don't understand it then you can't work reliably with the DOM, either with or without jQuery. Bottom line: use prop().
- donalm 15y agoYou could use it to test if the value has been changed.