0

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;
}
Ashok
  • 59
  • 1
  • 10
  • Make sure that the script is run after the DOM is ready, move it to the bottom of you document and try again. – Egil Hansen May 01 '22 at 16:29
  • you have an uppercase T in "Title". just use `document.querySelector('.title').style.backgroundColor = '#fff';` – chovy May 01 '22 at 16:46

2 Answers2

0

I believe you should be using backgroundColor - see example link

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

rbb
  • 1
  • 1
  • 3
0

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>