Why is there a difference between setting an input value via setAttribute or directly?

In devtools, run the following two lines:

1.

window.x = document.createElement("input"); x.type="text"; x.name="nm"; x.value="val"; x // <input type="text" name="nm"> 

2.

 window.x = document.createElement("input"); x.type="text"; x.name="nm"; x.setAttribute("value", "val"); x // <input type="text" name="nm" value="val"> 

Why will it print differently? The value appears to be correctly set in both cases. There seems to be a gap between the property and the DOM attribute.

Also, the getter property for the .value property becomes different than the result of .getAttribute('value') . I can setAttribute() all day, but .value returns the old value.

+6
source share
1 answer

The main difference between the two approaches is to set the base defaultValue property. when you use setAttribute , both defaultValue properties as well as value property will be updated / set. whereas using .value will only update / set the value property.

Behavior 1: (setting value using setAttribute)

 x.setAttribute("value","test"); x.defaultValue; //"test" x.value; //"test" 

Behavior 2: (value of a value directly using the value property)

 x.value = "test"; x.defaultValue; //"" x.value; //"test" 
+2
source

All Articles