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

How to set background color of HTML element

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

17 Answers

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

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.

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

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

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

Or, using a little jQuery:

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

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

Add this script element to your body element:

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

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

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

KISS Answer:

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

how can we do it for class?

For class document.getElementByClass('element').style.background = '#DD00DD';

You can do it with JQuery:

$(".class").css("background","yellow");
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript

so many ways are there I think it is very easy and simple

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

You can use:

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

you can use

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

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

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

A simple js can solve this:

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

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.

How can I make the browser see CSS and Javascript changes?

How see CSS and Javascript changes

CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion. Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. Could use the SVN revision number to automate this for you: ASP . NET Display SVN Revision Number Can you specify how you include the Revision variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file. In the Subversion book it says about Revision: "This keyword describes the last known revision in which this file changed in the repository". Firefox also allows pressing CTRL+R to reload everything on a particular page. To…

Read more…

How can I detect if a browser is blocking a popup? - JavaScript

Detect if a browser is blocking a popup

Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening. What methods can the calling window use to make sure the new window launched properly? 9 Answers If you use JavaScript to open the popup, you can use something like this: var newWin = window.open(url); if(!newWin || newWin.closed || typeof newWin.closed=='undefined') { //POPUP BLOCKED } Here's an answer for chrome: detect-blocked-popup-in-chrome @ajwaka could you kindly clarify if this answer fails for chrome, or is there a reason the other answer is better for chrome…

Read more…

How do I delimit a databound Javascript string parameter in ASP . NET?

Javascript string parameter in ASP . NET

Triple Quotes? How do I delimit a databound Javascript string parameter in ASP . NET? How do I delimit a Javascript data-bound string parameter in an anchor OnClick event? I have an anchor tag in an ASP . NET Repeater control. The OnClick event of the anchor contains a call to a Javascript function. The Javascript function takes a string for its input parameter. The string parameter is populated with a data-bound value from the Repeater. I need the "double quotes" for…

Read more…