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 {
    background:#ff00aa;
}

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)
{
    element.style.backgroundColor = color;
}

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

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

document.body.style.backgroundColor = "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:

$(".class").css("background","yellow");

Answer #8

You can use:

  <script type="text/javascript">
     Window.body.style.backgroundColor = "#5a5a5a";
  </script>

Answer #9

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>

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');
element.style.backgroundColor = "color or color_code";

Example.

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

JSFIDDLE


Answer #12

you can use

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

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




css