Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the difference between setting the value of an input via setAttribute or directly? [duplicate]

Tags:

javascript

dom

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.

like image 839
Madd0g Avatar asked Apr 07 '16 08:04

Madd0g


People also ask

What is setAttribute function used for?

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

Does setAttribute overwrite?

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.

Why is setAttribute not working?

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

What method allows us to add an attribute to a DOM element?

The setAttribute() method sets a new value to an attribute.


1 Answers

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"
like image 114
Rajaprabhu Aravindasamy Avatar answered Oct 01 '22 00:10

Rajaprabhu Aravindasamy