18

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

5

2 Answers 2

33

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

Sign up to request clarification or add additional context in comments.

3 Comments

this explains the behavior that I'm seeing. Thanks :)
quick question @Mark... why is it that if I do Element.attributes on a, say, input element, which basically represents key/value pair of strings describing any information regarding that attribute, I don't see the value attribute (that stores the actual value that that input contains)... it gives me a NamedNodeMap object with basically contains some attributes but not the value attribute, which holds the actual value. However if I do something like thatInput.value I can, ofc, see the value. Why is value not in the attributes property of the Element object?
Is value="" present on the Element itself? It won't show up on the list (I believe) if it wasn't already specified there, that might be why it's not showing up! But for example if I do document.querySelector('#test').attributes.value I see value="" of a blank new input textbox @MariusMucenicu
13

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

1 Comment

@ama2 my point is that .value is not the same as the attribute "value", but .defaultValue is. That's the reason, it's a bit unintuitive. Please consider jsfiddle.net/J9Mat/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.