2

Unable to get why elem.getAttribute("someAttribute") doesn't return updated value.

<body>
  <input type="text" value="previousValue">
  <script>
    var input = document.body.children[0]
 
    input.value = 'newValue'
 
    alert(input.getAttribute('value')) // 'previousValue', not changed!
  </script>
</body>

Can anyone explain this?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70

3 Answers3

5

While it's true that some of the properties on element instances are direct reflections of attributes (the rel property directly reflects the rel attribute on link elements, for instance, and className directly reflects the class attribute), but this isn't always the case.

The value property is not a direct reflection of the value attribute. It gets its initial value from the attribute, but setting it doesn't affect the attribute (which is still available both through getAttribute and the defaultValue property). (There are others that aren't direct reflections; the href property on a elements gives you the absolute path, but the href attribute may be a relative path.)

If you want to set the attribute, use setAttribute. (And test carefully on any versions of IE you want to support, as Microsoft has a history of getting this wrong.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 2
    @ShoaibChikate here's another excellent post by TJ which explains HTML attributes vs DOM properties more in-depth: http://stackoverflow.com/a/5884994/1331430 and here's a more technical explanation of this specific behavior: http://stackoverflow.com/a/11779426/1331430 – Fabrício Matté Oct 30 '14 at 09:45
0

Try this, it's working:

<body>
    <input type="text" value="previousValue">
    <script>
        var input = document.body.children[0];
        input.setAttribute('value', 'newValue');
        alert(input.getAttribute('value')); // 'previousValue', not changed!
    </script>
</body>
arghtype
  • 4,376
  • 11
  • 45
  • 60
Magzhan
  • 51
  • 1
  • Trying and replacing the code will make me good document writer but not programmer. Hence make your answer better by giving explaination regarding why OP's code doesn't work. – Shoaib Chikate Oct 30 '14 at 08:48
0

We can Access Object In JS by Two Types

input.value or input[value]

So you have to use second one

    <body>
  <input type="text" value="previousValue">
  <script>
    var input = document.body.children[0]
 
    input[value] = 'newValue'
 
    alert(input.getAttribute('value')) // Now Changed
  </script>
</body>