change CSS background color in JavaScript

javascript change background color of element (13)

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

Answer #1

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

Answer #2

Or, using a little jQuery:

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

Answer #3

KISS Answer:

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

Answer #4

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;

Answer #5
$(".class")[0].style.background = "blue";

Answer #6
$("body").css("background","green"); //jQuery = "green"; //javascript

so many ways are there I think it is very easy and simple

Demo On Plunker

Answer #7

You can do it with JQuery:


Answer #8

You can use:

  <script type="text/javascript"> = "#5a5a5a";

Answer #9

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

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

Answer #10
$('#ID / .Class').css('background-color', '#FF6600');

By using jquery we can target the element's class or Id to apply css background or any other stylings

Answer #11

You can try this

var element = document.getElementById('element_id'); = "color or color_code";


var element = document.getElementById('firstname'); = "green";//Or #ff55ff


Answer #12

you can use

$('#elementID').css('background-color', '#C0C0C0');

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