Create an input field using pure Javascript

Enrique Moreno OB picture Enrique Moreno OB · Jun 21, 2013 · Viewed 50.9k times · Source

Im trying to create such element only with JS:

<input type="text" value="default">

To do so, I tried this code:

var mi = document.createElement("input");
mi.type= "text"
mi.value = "default"

But when I run it in Chrome Dev Tools, it only creates this element:

<input type="text">

What am I missing?

Answer

Paul S. picture Paul S. · Jun 21, 2013

Setting a property of a HTMLElement isn't exactly the same as setting it's attribute to the same thing.

You most likely wanted to use element.setAttribute

var mi = document.createElement("input");
mi.setAttribute('type', 'text');
mi.setAttribute('value', 'default');

Now you can see

new XMLSerializer().serializeToString(mi);
// "<input type="text" value="default">"

In your example, the value displayed by the <input> will still be default, it just isn't set as the attribute.

Further note that if the user changes the value of <input>, e.g. types into it, setting the attribute will not change the value any longer, but setting the value property will still change it. Again, this is because an attribute is different to a property.