SetAttribute () does not work as I expect

this line of code:

document.getElementById('01').getElementsByTagName("input")[0].setAttribute("value", "1");


works great when "enter" doesn't matter yet. but when the input already has a value, it won't change the value. Why is this?


source to share

3 answers

It looks like you are facing confusing difference between element attribute value

and value

. It is not the same.

The point is that the value attribute serves as a default value, so if the element already has a property value, then the change in the value attribute will not be reflected in the user interface.

The documentation says this :

Using setAttribute () to change certain attributes, especially the value in XUL, is inconsistent because the attribute indicates a default value. To access or change the current values, you must use properties. For example, use elt.value instead of elt.setAttribute ('value', val).

So, to demonstrate this situation, consider this small demo:

document.getElementById("01").getElementsByTagName("input")[0].value = 'property set';

document.getElementById("01").getElementsByTagName("input")[0].setAttribute("value", "two");

<div id="01">
    <input type="text" />

Run codeHide result

In the snippet above, the value attribute does indeed update to the value two

and you can check it if you try to read it with getAttribute('value')

, however the value property takes precedence over the attribute so it is not displayed later.



That JavaScript absolutely changes the meaning of the tag <input>

when the tag already has an attribute value

. See it here:



for input field, if you want to set a value, just use value

Pure javascript:

document.getElementById('01').getElementsByTagName("input")[0].value = "value"







All Articles