[javascript] How to set background color of HTML element using css properties in JavaScript

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

This question is related to javascript css background-color

The answer is


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


Or, using a little jQuery:

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

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

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:

_x000D_
_x000D_
colors = ['rosybrown', 'cornflowerblue', 'pink', 'lightblue', 'lemonchiffon', 'lightgrey', 'lightcoral', 'blueviolet', 'firebrick', 'fuchsia', 'lightgreen', 'red', 'purple', 'cyan']_x000D_
_x000D_
let i = 0_x000D_
setInterval(() => {_x000D_
  const random = Math.floor(Math.random()*colors.length)_x000D_
  document.querySelector('.box').style.background = colors[random];_x000D_
}, 500)
_x000D_
.box {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_


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:

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


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:

_x000D_
_x000D_
document.querySelector('.box').classList.toggle('orange')
_x000D_
.box {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
.orange {_x000D_
  background: orange;_x000D_
}
_x000D_
<div class='box'></div>
_x000D_
_x000D_
_x000D_


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

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

_x000D_
_x000D_
var element = document.getElementById('element');_x000D_
_x000D_
element.onclick = function() {_x000D_
  element.classList.add('backGroundColor');_x000D_
  _x000D_
  setTimeout(function() {_x000D_
    element.classList.remove('backGroundColor');_x000D_
  }, 2000);_x000D_
};
_x000D_
.backGroundColor {_x000D_
    background-color: green;_x000D_
}
_x000D_
<div id="element">Click Me</div>
_x000D_
_x000D_
_x000D_


You can use:

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

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

you can use

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

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

A simple js can solve this:

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

KISS Answer:

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

$("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


Add this script element to your body element:

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

You can do it with JQuery:

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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to background-color

SwiftUI - How do I change the background color of a View? How to add a color overlay to a background image? How to change the background color on a input checkbox with css? How to change DatePicker dialog color for Android 5.0 Set Background color programmatically How to change the background-color of jumbrotron? Set textbox to readonly and background color to grey in jquery Change the background color of a pop-up dialog Background color of text in SVG Change background color of iframe issue