0

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

  • possible duplicate of [How do I change the background color with JavaScript?](http://stackoverflow.com/questions/197748/how-do-i-change-the-background-color-with-javascript) –  Mar 23 '14 at 18:17

2 Answers2

4

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

It should be mydiv.style.backgroundColor

Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168