-2

New to JavaScript and HTML. I'm trying to change the background color in my HTML code through JavaScript.

The only thing that I need to happen is to change the background color on divMain below from black to white using only JavaScript and keeping the HTML code the same

<style>

#divMain {
position:absolute;
left:0px;
top:0px;
width:320px;
height:460px;
background-color:black;
-webkit-user-select:none;
-webkit-text-size-adjust:none;
}

</style>

</head>

<body 
onload="body_load();" 
>

<div 
id="divMain">
</div>

The only things that I have in the JavaScript code is this:

function body_load() {
}
Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
Mark Shimala
  • 65
  • 10
  • 2
    Have you tried anything? – j08691 Feb 01 '14 at 17:46
  • Thanks, that helps a little bit but I don't see how to change it inside of a div tag. Only how to change the background of the body – Mark Shimala Feb 01 '14 at 17:47
  • This question appears to be off-topic because it is about absolute basics, that you should read up on in some tutorial or other. – CBroe Feb 01 '14 at 17:49
  • This question has an answer to set it for a specific element: http://stackoverflow.com/questions/3319/css-background-color-in-javascript – maja Feb 01 '14 at 17:50
  • why you need this? you can't modify the bg color with CSS? the link above (answer from @ryanulit ) solve your question. – Joe RR Feb 01 '14 at 17:50

2 Answers2

2

If you want to change the background of an element, you can use this:

document.getElementById("divMain").style.backgroundColor = "#FF0000";

It will change the div-Background to red. But why do you want to make this with javascript?

Solve it with inline-CSS:

<div id="divMain" style="background-color: red"></div>
maja
  • 17,250
  • 17
  • 82
  • 125
0

document.getElementById("divMain").style.backgroundColor="red" e.g.

Amir Sherafatian
  • 2,083
  • 2
  • 20
  • 32