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?


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)
{ = 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 {

Then in JavaScript:

element.className = element.className === 'highlight' ? '' : 'highlight';

Solution 3:

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

Solution 4:

Or, using a little jQuery:

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

Solution 5:

Add this script element to your body element:

  <script type="text/javascript"> = "#AAAAAA";

Solution 6:

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

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