In devtools, run these 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 would it get printed differently? The value seems to be set properly in both cases. It seems like there's a disconnect between the property and the DOM attribute.
Also the getter for property .value becomes different than the result of .getAttribute('value'). I can setAttribute() all day, but .value returns old value.
setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .
Using setAttributeIf the attribute is already assigned to an element, the value is overwritten. If not, elements are assigned a new attribute with indicated values and name.
The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).
The setAttribute() method sets a new value to an attribute.
The main difference between both the approach is setting the underlying defaultValue property. when you use setAttribute, the both defaultValue property as well as the value property will be updated/set. whereas using .value will update/set the value property of it only.
Behavior 1: (setting value using setAttribute)
x.setAttribute("value","test");
x.defaultValue; //"test"
x.value; //"test"
Behavior 2: (setting value directly using value property)
x.value = "test";
x.defaultValue; //""
x.value; //"test"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With