How to set background color of HTML element using css properties in JavaScript

How can I set the background color of an HTML element using css in JavaScript?


Solution 1:

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;
}

// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');

Solution 2:

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';

Solution 3:

var element = document.getElementById('element');
element.style.background = '#FF00AA';

Solution 4:

Or, using a little jQuery:

$('#fieldID').css('background-color', '#FF6600');

Solution 5:

Add this script element to your body element:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>