How can I create and style a div using JavaScript?

后端 未结 9 2312
野的像风
野的像风 2020-11-27 10:27

How can I use JavaScript to create and style (and append to the page) a div, with content? I know it\'s possible, but how?

9条回答
  •  伪装坚强ぢ
    2020-11-27 10:48

    var div = document.createElement("div");
    div.style.width = "100px";
    div.style.height = "100px";
    div.style.background = "red";
    div.style.color = "white";
    div.innerHTML = "Hello";
    
    document.getElementById("main").appendChild(div);
    
    

    var div = document.createElement("div");
    div.style.width = "100px";
    div.style.height = "100px";
    div.style.background = "red";
    div.style.color = "white";
    div.innerHTML = "Hello";
    
    document.getElementById("main").appendChild(div);
    OR
    document.body.appendChild(div);
    

    Use parent reference instead of document.body.

提交回复
热议问题