How to set background color of HTML element using css properties in JavaScript
Asked Answered
I

17

129

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

Iraidairan answered 6/8, 2008 at 12:23 Comment(0)
D
167

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');
Depute answered 6/8, 2008 at 12:25 Comment(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 answerMccrory
In Selenium tests: ((IJavaScriptExecutor)WebDriver).ExecuteScript("arguments[0].style.background = 'yellow';", webElement);Dib
@Mccrory 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.Censorious
L
31

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';
Leavetaking answered 19/8, 2008 at 11:59 Comment(2)
I'd say that it's obvious where to put it - anywhere after the HTML you want to change.Rudie
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 ;)Serriform
A
25
var element = document.getElementById('element');
element.style.background = '#FF00AA';
Adeleadelheid answered 6/8, 2008 at 12:25 Comment(0)
T
21

Or, using a little jQuery:

$('#fieldID').css('background-color', '#FF6600');
Thickknee answered 6/8, 2008 at 13:23 Comment(1)
Most likely, as the OP has asked for Javascript ;)Doddering
O
7

Add this script element to your body element:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>
Overhang answered 3/3, 2011 at 21:20 Comment(0)
S
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>
Segalman answered 17/4, 2015 at 16:7 Comment(0)
B
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

Bide answered 3/9, 2015 at 12:21 Comment(1)
element.style.background-color isn't valid JavaScript. That's why CSS properties are converted to CamelCase.Inexperience
N
4

KISS Answer:

document.getElementById('element').style.background = '#DD00DD';
Nessus answered 1/3, 2013 at 23:57 Comment(2)
how can we do it for class?Kettie
For class document.getElementByClass('element').style.background = '#DD00DD';Octad
C
4

You can do it with JQuery:

$(".class").css("background","yellow");
Clovah answered 10/2, 2014 at 17:13 Comment(0)
H
3

You can use:

<script type="text/javascript">
  Window.body.style.backgroundColor = "#5a5a5a";
</script>
Hyperpituitarism answered 5/1, 2014 at 12:51 Comment(0)
P
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

Periclean answered 13/3, 2017 at 20:51 Comment(0)
C
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

Catalogue answered 23/6, 2017 at 9:56 Comment(0)
B
1

you can use

$('#elementID').css('background-color', '#C0C0C0');
Bots answered 11/4, 2014 at 1:34 Comment(3)
this is jquery not javascriptKettie
@vignesh jQuery is JavaScript -__-Headwards
@Headwards jQuery is written using JavaScript, Yes. but still $ is not gonna work unless you include that jQuery library ;)Kettie
E
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
Endue answered 7/6, 2018 at 19:51 Comment(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.Submultiple
C
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
Cotswold answered 23/6, 2017 at 10:2 Comment(0)
R
0

A simple js can solve this:

document.getElementById("idName").style.background = "blue";
Resemblance answered 20/1, 2020 at 8:38 Comment(0)
C
-1
$(".class")[0].style.background = "blue";
Callant answered 11/11, 2015 at 8:44 Comment(2)
There's more than enough correct answers to this question, and this answer does not offer anything better than other answers.Headwards
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.Uird

© 2022 - 2024 — McMap. All rights reserved.