To do th...">

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?

+6
source share
3 answers

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.

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

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

0
source

Source: https://habr.com/ru/post/947831/


All Articles