How can I create and style a div using JavaScript?

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

    Here's one solution that I'd use:

    var div = '
    blah
    ';

    If you wanted the attribute and/or attribute values to be based on variables:

    var id = "hello";
    var classAttr = "class";
    var div = '
    Blah
    ';

    Then, to append to the body:

    document.getElementsByTagName("body").innerHTML = div;
    

    Easy as pie.

提交回复
热议问题