130

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

17 Answers 17

168

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');
3
  • 3
    I'd like to add the color obviously needs to be in quotes element.style.backgroundColor = "color"; for example - element.style.backgroundColor = "orange"; excellent answer
    – Catto
    Commented Jul 1, 2016 at 17:05
  • In Selenium tests: ((IJavaScriptExecutor)WebDriver).ExecuteScript("arguments[0].style.background = 'yellow';", webElement);
    – nexoma
    Commented Mar 15, 2018 at 12:31
  • @Catto In this case, color is an argument to the function, hence it should not be in quotes. However, you are right that normally, if setting a color, double quotes would be necessary in JS. Commented Mar 24, 2018 at 5:37
32

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';
2
  • 2
    I'd say that it's obvious where to put it - anywhere after the HTML you want to change.
    – TeeJay
    Commented Sep 26, 2014 at 14:52
  • 1
    This is valid in most cases, but not in cases where the color (or whatever attribute) is defined in configuration, or user entered, you can't create a CSS class for every possible color ;) Commented Apr 17, 2015 at 16:20
26
var element = document.getElementById('element');
element.style.background = '#FF00AA';
21

Or, using a little jQuery:

$('#fieldID').css('background-color', '#FF6600');
1
  • Most likely, as the OP has asked for Javascript ;)
    – Lodder
    Commented Mar 18, 2014 at 11:07
7

Add this script element to your body element:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>
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>

5

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

1
  • 1
    element.style.background-color isn't valid JavaScript. That's why CSS properties are converted to CamelCase. Commented Sep 30, 2015 at 17:24
4

KISS Answer:

document.getElementById('element').style.background = '#DD00DD';
2
  • how can we do it for class? Commented Feb 26, 2015 at 3:54
  • For class document.getElementByClass('element').style.background = '#DD00DD';
    – MD Ashik
    Commented Nov 4, 2016 at 17:21
4

You can do it with JQuery:

$(".class").css("background","yellow");
3
$("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

3
$('#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

3

You can use:

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

you can use

$('#elementID').css('background-color', '#C0C0C0');
3
  • this is jquery not javascript Commented Feb 26, 2015 at 3:54
  • @vignesh jQuery is JavaScript -__-
    – Novocaine
    Commented Nov 11, 2015 at 9:53
  • @Novocaine jQuery is written using JavaScript, Yes. but still $ is not gonna work unless you include that jQuery library ;) Commented Nov 11, 2015 at 10:20
1

Changing CSS of a HTMLElement

You can change most of the CSS properties with JavaScript, use this statement:

document.querySelector(<selector>).style[<property>] = <new style>

where <selector>, <property>, <new style> are all String objects.

Usually, the style property will have the same name as the actual name used in CSS. But whenever there is more that one word, it will be camel case: for example background-color is changed with backgroundColor.

The following statement will set the background of #container to the color red:

documentquerySelector('#container').style.background = 'red'

Here's a quick demo changing the color of the box every 0.5s:

colors = ['rosybrown', 'cornflowerblue', 'pink', 'lightblue', 'lemonchiffon', 'lightgrey', 'lightcoral', 'blueviolet', 'firebrick', 'fuchsia', 'lightgreen', 'red', 'purple', 'cyan']

let i = 0
setInterval(() => {
  const random = Math.floor(Math.random()*colors.length)
  document.querySelector('.box').style.background = colors[random];
}, 500)
.box {
  width: 100px;
  height: 100px;
}
<div class="box"></div>


Changing CSS of multiple HTMLElement

Imagine you would like to apply CSS styles to more than one element, for example, make the background color of all elements with the class name box lightgreen. Then you can:

  1. select the elements with .querySelectorAll and unwrap them in an object Array with the destructuring syntax:

    const elements = [...document.querySelectorAll('.box')]
    
  2. loop over the array with .forEach and apply the change to each element:

    elements.forEach(element => element.style.background = 'lightgreen')
    

Here is the demo:

const elements = [...document.querySelectorAll('.box')]
elements.forEach(element => element.style.background = 'lightgreen')
.box {
  height: 100px;
  width: 100px;
  display: inline-block;
  margin: 10px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>


Another method

If you want to change multiple style properties of an element more than once you may consider using another method: link this element to another class instead.

Assuming you can prepare the styles beforehand in CSS you can toggle classes by accessing the classList of the element and calling the toggle function:

document.querySelector('.box').classList.toggle('orange')
.box {
  width: 100px;
  height: 100px;
}

.orange {
  background: orange;
}
<div class='box'></div>


List of CSS properties in JavaScript

Here is the complete list:

alignContent
alignItems
alignSelf
animation
animationDelay
animationDirection
animationDuration
animationFillMode
animationIterationCount
animationName
animationTimingFunction
animationPlayState
background
backgroundAttachment
backgroundColor
backgroundImage
backgroundPosition
backgroundRepeat
backgroundClip
backgroundOrigin
backgroundSize</a></td>
backfaceVisibility
borderBottom
borderBottomColor
borderBottomLeftRadius
borderBottomRightRadius
borderBottomStyle
borderBottomWidth
borderCollapse
borderColor
borderImage
borderImageOutset
borderImageRepeat
borderImageSlice
borderImageSource  
borderImageWidth
borderLeft
borderLeftColor
borderLeftStyle
borderLeftWidth
borderRadius
borderRight
borderRightColor
borderRightStyle
borderRightWidth
borderSpacing
borderStyle
borderTop
borderTopColor
borderTopLeftRadius
borderTopRightRadius
borderTopStyle
borderTopWidth
borderWidth
bottom
boxShadow
boxSizing
captionSide
clear
clip
color
columnCount
columnFill
columnGap
columnRule
columnRuleColor
columnRuleStyle
columnRuleWidth
columns
columnSpan
columnWidth
counterIncrement
counterReset
cursor
direction
display
emptyCells
filter
flex
flexBasis
flexDirection
flexFlow
flexGrow
flexShrink
flexWrap
content
fontStretch
hangingPunctuation
height
hyphens
icon
imageOrientation
navDown
navIndex
navLeft
navRight
navUp>
cssFloat
font
fontFamily
fontSize
fontStyle
fontVariant
fontWeight
fontSizeAdjust
justifyContent
left
letterSpacing
lineHeight
listStyle
listStyleImage
listStylePosition
listStyleType
margin
marginBottom
marginLeft
marginRight
marginTop
maxHeight
maxWidth
minHeight
minWidth
opacity
order
orphans
outline
outlineColor
outlineOffset
outlineStyle
outlineWidth
overflow
overflowX
overflowY
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
pageBreakAfter
pageBreakBefore
pageBreakInside
perspective
perspectiveOrigin
position
quotes
resize
right
tableLayout
tabSize
textAlign
textAlignLast
textDecoration
textDecorationColor
textDecorationLine
textDecorationStyle
textIndent
textOverflow
textShadow
textTransform
textJustify
top
transform
transformOrigin
transformStyle
transition
transitionProperty
transitionDuration
transitionTimingFunction
transitionDelay
unicodeBidi
userSelect
verticalAlign
visibility
voiceBalance
voiceDuration
voicePitch
voicePitchRange
voiceRate
voiceStress
voiceVolume
whiteSpace
width
wordBreak
wordSpacing
wordWrap
widows
writingMode
zIndex
1
  • Been looking for proper documentation on MDN or elsewhere for this convention and list but unable to find. Adding references to the answer will help a lot. Thanks.
    – trss
    Commented Jun 23, 2023 at 10:04
0

Javascript:

document.getElementById("ID").style.background = "colorName"; //JS ID

document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class

Jquery:

$('#ID/.className').css("background","colorName") // One style

$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style
0
0

A simple js can solve this:

document.getElementById("idName").style.background = "blue";
-1
$(".class")[0].style.background = "blue";
2
  • There's more than enough correct answers to this question, and this answer does not offer anything better than other answers.
    – Novocaine
    Commented Nov 11, 2015 at 9:55
  • As Novocaine said there's plenty of answers here. But in future please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. Commented Nov 11, 2015 at 11:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.