Take the 2-minute tour ×

How can I set the CSS background color of an HTML element via JavaScript?

share|improve this question

9 Answers 9

up vote 73 down vote accepted

In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So background-color becomes backgroundColor.

function setColor(element, color)
    element.style.backgroundColor = color;
share|improve this answer
Thank man! for this answer. –  Maddy Sep 15 at 6:55

You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.

Your CSS would obviously be something like:

.highlight {

Then in JavaScript:

element.className = element.className === 'highlight' ? '' : 'highlight';
share|improve this answer
ermm yes Javascript but where do you put it??!!! not clear enough –  Clash Aug 12 at 20:03
I'd say that it's obvious where to put it - anywhere after the HTML you want to change. –  TeeJay Sep 26 at 14:52
var element = document.getElementById('element');
element.style.background = '#ff00aa';
share|improve this answer

Or, using a little jQuery:

$('#fieldID').css('background-color', '#FF6600');
share|improve this answer
Are the downvotes because I referenced jQuery? just curious –  Wally Lawless Dec 19 '13 at 13:30
Most likely, as the OP has asked for Javascript ;) –  Lodder Mar 18 at 11:07

Add this script element to your body element:

  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
share|improve this answer

You can use:

  <script type="text/javascript">
     Window.body.style.backgroundColor = "#5a5a5a";
share|improve this answer

You can do it with jquery. $(".class").css("background","yellow");

share|improve this answer

KISS Answer:

document.getElementById('element').style.background = '#DD00DD';
share|improve this answer

you can use

$('#elementID').css('background-color', '#C0C0C0');
share|improve this answer

Your Answer


