Create an input field using pure Javascript
I am trying to create such an element using JS only:
<input type="text" value="default"> To do this, 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?
Setting the HTMLElement property is not quite the same as setting the attribute for the same thing.
You most likely would like 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 <input> will still be default , it just isn't set as an attribute.
It should be noted further that if the user changes the value of <input> , for example. types into it, setting the attribute will no longer change the value, but setting the value property will still change it. Again, this is because the attribute is different from the property.