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
2008-08-06 12:25:13
+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
2008-08-06 12:25:54
+4
A:
Or, using a little jQuery:
$('#fieldID').css('background-color', '#FF6600');
Wally Lawless
2008-08-06 13:23:42
+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
2008-08-19 11:59:40