Calicol Calicol - 25 days ago 6
HTML Question

How do I create this with javascript

<div>
<div></div>
<div></div>
</div>


I want to create a DIV then create two more DIVS inside the firstone using javascript

i tried

var div = document.createElement("div");
div.id = "square";
document.getElementById("main").appendChild(div);
var div1 = document.createElement("div");
var div2 = document.createElement("div");
document.getElementById("square").appendChild(div1);
document.getElementById("square").appendChild(div2);


But it doesn't work...

Answer

document.getElementById("main")? You don't need to assign the first div an id, either.

var div0 = document.createElement("div");
var div1 = document.createElement("div");
var div2 = document.createElement("div");
div0.appendChild(div1);
div0.appendChild(div2);
document.body.appendChild(div0);