'How to change background color of div [duplicate]
How shall change background color for below css using jquery
When tried using this it show me error of undefined
var element = document.getElementsByClassName('Title');
element.style.background = '#FF00AA';
Uncaught TypeError: Cannot set properties of undefined (setting 'background')
.orgchart .node .title {
position: relative!important;
text-align: center!important;
font-size: 12px!important;
font-weight: bold!important;
height: 20px!important;
line-height: 20px!important;
overflow: hidden!important;
text-overflow: ellipsis!important;
white-space: nowrap!important;
background-color: #eb3c96!important;
color: #fff!important;
border-radius: 4px 4px 0 0!important;
font-family: Calibri !important;
width: 185px!important;
}
Solution 1:[1]
I believe you should be using backgroundColor - see example link
https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp
Solution 2:[2]
First of all, document.getElementsByClassName returns an array-like HTMLCollection object. You should access an element of this collection to set the element's style properties, otherwise you get an undefined value, as described in the mozilla docs in the 4th example.
Second, the background is a shorthand for a handful of other properties, if you only change the background color of an element, you should probably use the more specific backgroundColor property, like the comment mentioned.
I have written a small script, which sets the background color of the first (and only) element using the class name. You can run it to view the results.
More info on document.getElementsByClassName here and on style.background here.
// access the first element of the array with [0]
const divToChange = document.getElementsByClassName('Title')[0];
// use the more specific 'backgroundColor' property if possible
divToChange.style.backgroundColor = "#FF00AA";
<h3 class="Title">Change my background</h3>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rbb |
| Solution 2 |
