Hacker News new | past | comments | ask | show | jobs | submit login

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.




Question: 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.


The 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().


You could use it to test if the value has been changed.


Thank you! The pure definition of simpler terms I was looking for. Going through my code now to see if I need to make changes!


Note 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: