Add a Style Attribute to Div using Javascript function

Hi All,

I have a DIV  container and I would like to be able to add"background:#color"... through a javascript function of which the background colour is passed in as a argument..

function OpenDialog(strColour)
 Apply background style to MyDivId.

Many thanks,

Who is Participating?
Richard QuadlingConnect With a Mentor Senior Software DeveloperCommented:
Are you using a JS library? I use Prototype (

Using prototype, I would do ...


NOTE: strColor needs to be look like #aabbcc where aa, bb, cc are the hex values for the RGB colours.

Albert Van HalenConnect With a Mentor Analyst developerCommented:
No need for libraries. Although it makes life much easier (my personal fav is jquery)
document.getElementById(myDivId).style.backgroundColor = strColor; // strColor being #rrggbb like RQuadling said (#ff0000 for red) or a named color like : red
via jQuery:
$("#" + myDivId).css("backgroundColor", strColor); 

Open in new window

Richard QuadlingSenior Software DeveloperCommented:
Albert is right about the libs. But I just find them so useful for consistency and provide some support for features lacking on older browsers.
rito1Author Commented:
Thanks both. Much appreciated.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.