Question

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?

Était-ce utile?

La solution

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.

Autres conseils

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
i.setAttribute('value',"default");

I think you are missing the ; after "text".

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top