Home > Software design >  How to change background color of div
How to change background color of div

Time:05-02

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

CodePudding user response:

I believe you should be using backgroundColor - see example link

https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp

CodePudding user response:

First of all, document.getElementsByClassName returns an array of objects, you should access an element from the array to set its style properties, I believe that is why you get an undefined value, the mozilla docs say this at 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 you can run 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 >Change my background</h3>

  • Related