user3452886
user3452886

Reputation: 11

creating div using javascript

I tried to create div using javascript, but struck up at one point. Here is the code.

<script type="text/javascript">

    var mydiv = document.createElement("div");
    mydiv.id = "div1";
    mydiv.style.height = "200px";
    mydiv.style.width = "200px";
    mydiv.style.background-color = "red";

    document.body.appendChild(mydiv);

Your help is highly obliged.

Thanks in advance

Upvotes: 0

Views: 75

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075527

background-color is an invalid identifier in JavaScript. You can use backgroundColor instead.

mydiv.style.backgroundColor = "red";

Any CSS property with a dash in it is done in camelCase on the style object. So backgroundColor, marginLeft, etc. The values you assign are strings, so this doesn't apply to them, just the property names.

Upvotes: 4

Muhammad Umer
Muhammad Umer

Reputation: 18159

It should be mydiv.style.backgroundColor

Upvotes: 0

Related Questions