How to Set Background Color of HTML Element Using CSS Properties in JavaScript

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

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

How to change in javascript background color from css

You are attempting to set the background colour of the <style> tag. This is not how it works. Instead of setting the style of the <style> tag, you should set the style of the body itself. This W3Schools Article gives an explanation if you need one.

<head>
<style>
body {
background-color: pink;
}
</style>
</head>

<body id="1">

<script>
document.getElementById("1").style.backgroundColor = "brown";
</script>
</body>

It's also worth noting you don't need to assign the element to a variable unless you are going to use it later.

How to get backgroundColor of element when it is set by the CSS property background?

When you access the style (ElementCSSInlineStyle.style) property of an element, you are accessing its inline style. This means that if you give an element a style via a class, you still cannot access it through style. As a result, it will return you an empty string ('').

Window.getComputedStyle, on the other hand, returns:

... the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain

This means that you can access the style that is given via a class, simply because it gives you all CSS properties after applying all active stylesheets (including those applied via a class).

In your particular case, you're trying to access background. background CSS property is actually a shorthand that also sets a lot of other background-related CSS properties. When you specify only the color using background, the other properties will automatically be inserted with their default values. You can access this background property through ElementCSSInlineStyle.style. However, when accessing background in the object Window.getComputedStyle returns, you will always get an empty string. This is because the object returned does not have the key background; it only has the keys for each background-related CSS properties (e.g. background-color, background-clip, etc.).

Here's a simple example demonstrating how you cannot access a non-inline style through style property of an element, and also how you cannot access the value of a property that is shorthand through the object Window.getComputedStyle

const boxOne = document.querySelector('#boxOne')const boxTwo = document.querySelector('#boxTwo')
console.log(`Box One: background ${boxOne.style['background']}, background-color ${boxOne.style['background-color']}`)
console.log(`Box Two: background ${boxTwo.style['background']}, background-color ${boxTwo.style['background-color']}`)
const boxOneComputedStyles = getComputedStyle(boxOne)const boxTwoComputedStyles = getComputedStyle(boxTwo)
// There's no 'background' key in getComputedStyle
console.log(`Box One (Computed Styles): background ${boxOneComputedStyles['background']}, background-color ${boxOneComputedStyles['background-color']}`)
console.log(`Box Two (Computed Styles): background ${boxTwoComputedStyles['background']}, background-color ${boxTwoComputedStyles['background-color']}`)
#boxOne,#boxTwo {  background: #121212DD;  border-radius: 5px;  width: 50px;  height: 50px;  margin: 1em;}
<div id="boxOne" style="background-color: #121212DD;"></div><div id="boxTwo" style="background: #121212DD;"></div>

Two ways to get background-color property using Javascript

Checkout this link

The getComputedStyle() method is used to get all the computed CSS property and values of the specified element. The use of computed style is displaying the element after stylings from multiple sources have been applied. The getComputedStyle() method returns a CSSStyleDeclaration object.

In other words, the returned value from both calls can be different, since the computed style will be the result of applying all rules for the element.
The element CSS reads what we set directly on the element, which can be overwritten by another rule on another element (its parent for example).

How do I change the background color with JavaScript?

Modify the JavaScript property document.body.style.background.

For example:

function changeBackground(color) {
document.body.style.background = color;
}

window.addEventListener("load",function() { changeBackground('red') });

Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.

How can i set the css background through javascript

The background property sets or returns up to eight separate background properties, in a shorthand form.

With this property, you can set/return one or more of the following (in any order):

background-color
background-image
background-repeat
background-attachment
background-position
background-size
background-origin
background-clip

Example:

object.style.background="color image repeat attachment position size origin clip|initial|inherit"

Using JS to add a background color to a dynamically created Div

The other solution is correct that the element does not exist by then. However, if you added more rows, those new rows/grid items will not have the event listener attached.

Instead, you can rely on a more versatile event delegation technique to ensure that all future grid items have the event listener:


// uses a loop to create the required divs
function makeRows(rows, cols) {
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', cols);

for (c = 0; c < (rows * cols); c++) {
let cell = document.createElement("div");
cell.classes = ['grid-item'];
cell.style.setProperty('height', '24px');
cell.style.setProperty('background-color', 'black');
container.appendChild(cell).className = "grid-item";
};
};

makeRows(16, 16);


function changeGridColor (e) {
e.style.backgroundColor="red";
};

document.addEventListener('click',function(e){
console.log(e.target.classes);
if(e.target && e.target.classes.includes('grid-item')){
changeGridColor(e.target);
}
});

We add the grid-item class and then setup a click event listener so that whenever a grid item class is clicked, the color is changed.

Here's a working jsfiddle: https://jsfiddle.net/1e7c2gzu/22/

(Also note you wouldn't see your grid items initially because they didn't have a size to them so I added a size and set them to black so you could see them)

Javascript: change color of the entire page

if you really want to change the colour of the whole page, you can just target body in your CSS, like

body{
background-color: red;
}

You can make this change in your index.css and add this line in your body selector.

body {
margin: 0;
background-color: red;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

IMPORTANT NOTE

There may be a case where you have elements with their own background colour, and they will continue to have that until to specifically change each element CSS. Changing body or html background colour won't impact individual elements.



Related Topics



Leave a reply



Submit