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?

3 Answers 3

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

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

1 Comment

@ShoaibChikate here's another excellent post by TJ which explains HTML attributes vs DOM properties more in-depth: stackoverflow.com/a/5884994/1331430 and here's a more technical explanation of this specific behavior: stackoverflow.com/a/11779426/1331430
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>

1 Comment

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

Comments

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.