ama2
ama2

Reputation: 2681

Difference between Element.value and Element.getAttribute("value")

I'm just wondering what the difference is between the two. I have noticed the two methods give different results at times.

Upvotes: 18

Views: 12865

Answers (2)

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66971

The difference is that element.value is real time and if a user changes let's say, a textbox input, it will reflect that, and show you the new value.

While getAttribute('value') will still show the original value="whateverWasHere" value.

jsFiddle DEMO

Upvotes: 33

Esailija
Esailija

Reputation: 140220

.value does not map to any attribute.

.defaultValue maps to the "value" attribute. So when you say elem.getAttribute("value") that's the same as elem.defaultValue.

Additionally, .defaultValue reflects .value when the input is untouched (dirty value flag is false). After the input's value is changed by user interaction, this mapping stops. While the input is untouched, you can change .defaultValue (and thus .setAttribute("value")) and see it change .value as well. Not that this is practically useful but interesting piece of trivia nevertheless.

Upvotes: 13

Related Questions