I'm just wondering what the difference is between the two. I have noticed the two methods give different results at times.
-
possible duplicate of To use getAttribute(), or not to use getAttribute(): that is the questionFelix Kling– Felix Kling2012-08-15 17:01:28 +00:00Commented Aug 15, 2012 at 17:01
-
1While this question refers to set instead of get, the information might help you.j08691– j086912012-08-15 17:01:58 +00:00Commented Aug 15, 2012 at 17:01
-
1@j08691 attributes that map to properties always reflect the current value of that property.Esailija– Esailija2012-08-15 17:08:47 +00:00Commented Aug 15, 2012 at 17:08
-
@j08691 yup that sums it up pretty wellama2– ama22012-08-15 17:13:38 +00:00Commented Aug 15, 2012 at 17:13
-
possible duplicate of When to use setAttribute vs .attribute= in JavaScript?Peter O.– Peter O.2012-12-05 05:16:09 +00:00Commented Dec 5, 2012 at 5:16
2 Answers
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.
3 Comments
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?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.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
.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