131

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');
Sign up to request clarification or add additional context in comments.

3 Comments

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
In Selenium tests: ((IJavaScriptExecutor)WebDriver).ExecuteScript("arguments[0].style.background = 'yellow';", webElement);
@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.
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 Comments

I'd say that it's obvious where to put it - anywhere after the HTML you want to change.
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 ;)
26
var element = document.getElementById('element');
element.style.background = '#FF00AA';

Comments

21

Or, using a little jQuery:

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

1 Comment

Most likely, as the OP has asked for Javascript ;)
7

Add this script element to your body element:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>

Comments

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>

Comments

5

KISS Answer:

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

3 Comments

how can we do it for class?
For class document.getElementByClass('element').style.background = '#DD00DD';
@MDAshik that should be getElementsByClassName developer.mozilla.org/en-US/docs/Web/API/Document/…
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 Comment

element.style.background-color isn't valid JavaScript. That's why CSS properties are converted to CamelCase.
4

You can do it with JQuery:

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

Comments

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

Comments

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

Comments

3

You can use:

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

Comments

1

you can use

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

3 Comments

this is jquery not javascript
@vignesh jQuery is JavaScript -__-
@Novocaine jQuery is written using JavaScript, Yes. but still $ is not gonna work unless you include that jQuery library ;)
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 Comment

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.
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

Comments

0

A simple js can solve this:

document.getElementById("idName").style.background = "blue";

Comments

-1
$(".class")[0].style.background = "blue";

2 Comments

There's more than enough correct answers to this question, and this answer does not offer anything better than other answers.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.