Difference between Element.value and Element.getAttribute(“value”)

前端 未结 2 1255
你的背包
你的背包 2020-11-29 08:45

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

相关标签:
2条回答
  • 2020-11-29 09:10

    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

    0 讨论(0)
  • 2020-11-29 09:11

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

    0 讨论(0)
提交回复
热议问题