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?
Approach 1: Use document. createElement() to create the new elements and use setAttribute() method to set the attributes of elements. Append these elements to the <form> element by appendChild() method. Finally append the <form> element to the <body> element of the document.
To create input fields, use createElement method and specify element name i.e. "input" as parameter like below and assign it to a variable. var textfield = document.
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.
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