How can I create and style a div using JavaScript?

后端 未结 9 2307
野的像风
野的像风 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 11:11

    Another thing I like to do is creating an object and then looping thru the object and setting the styles like that because it can be tedious writing every single style one by one.

    var bookStyles = {
       color: "red",
       backgroundColor: "blue",
       height: "300px",
       width: "200px"
    };
    
    let div = document.createElement("div");
    
    for (let style in bookStyles) {
     div.style[style] = bookStyles[style];
    }
    
    body.appendChild(div);
    

提交回复
热议问题