Why this for loop doesnt work?
javascript:
function create(){
var newDiv = document.createElement("input");
var character = "piyush";
var i =0;
newDiv.type = "text";
newDiv.style.background = "red";
newDiv.style.width ="20px";
newDiv.style.height ="20px";
for( i =0; i< character.length ; i++)
{
document.getElementById("tryingin").appendChild(newDiv);
}
}
html:
<div id="tryingin" onMouseOut="create()" style="width:200px; height:200px; background-color:black"> </div>
now when i alert something in the for loop . i see the alert box 6 times one after the other(as character.length == 6). but why i dont see 6 textboxes appended in the division?
And what should be the correct code to append all 6 textboxes all at once.
Help appreciated.
Regards!
If an element is already part of the DOM,
.appendChildwill first detach it from its current parent and attach it to the new parent. From the MDN documentation:In your case you only have one DOM element. If you want to duplicate the element, you can clone it: