tags:

views:

3135

answers:

4

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

+2  A: 
                    var element = document.getElementById('element');
element.style.background = '#ff00aa';
tags2k
+22  A: 

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;
}
Ch00k
+4  A: 

Or, using a little jQuery:

$('#fieldID').css('background-color', '#FF6600');
Wally Lawless
+5  A: 

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 { background:#ff00aa; }

Then in JavaScript:

element.className = (element.className === 'highlight' ? '' : 'highlight');
Ian Oxley