How to set CSS background color of HTML using JavaScript

How to set CSS background color of HTML using JavaScript

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

Solutions/Answers:

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

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>

Solution 6:

var element = document.getElementById('element');

element.onclick = function() {
  element.classList.add('backGroundColor');
  
  setTimeout(function() {
    element.classList.remove('backGroundColor');
  }, 2000);
};
.backGroundColor {
    background-color: green;
}
<div id="element">Click Me</div>