-3

For the following styles, how does one change the value of background color using javascript.

i)Internal Style sheet and/or ii) External Style sheet

I am using the card deck slide show from https://github.com/dynamicdriverepo/carddeckslideshow

div.stackcontainer > div.inner{ background: #D7F9FF; }

  • 2
    Possible duplicate of [Changing CSS Values with Javascript](https://stackoverflow.com/questions/566203/changing-css-values-with-javascript) – jhpratt Nov 18 '17 at 21:20

1 Answers1

0

One way would be to use a CSS variable (Only available in the latest browsers)

div.stackcontainer > div.inner{ background: var(--inner-bg-color, #D7F9FF); }

Then you can use JS to set the value for --inner-bg-color anywhere from div.inner or above.

document.querySelector('div.stackcontainer').style.setProperty('--inner-bg-color', 'red')

But if you can't change their CSS then you need to adjust the style for that element:

var el = document.querySelector('div.stackcontainer > div.inner');
if (el) {
  el.style.backgroundColor = '#FF0000';
}

Be aware that you are now messing with the specificity values that determine what CSS to use. And, if you want to reset to the original then you need to remove the style value from that element.

var el = document.querySelector('div.stackcontainer > div.inner');
if (el) {
  el.style.backgroundColor = '';
}
Intervalia
  • 10,248
  • 2
  • 30
  • 60
  • It worked and I am able to update the backgroundColor, however only the backgroundColor of top most card is changing rest of the stack continues with the default backgroundColor. – Kalyan Kumar Nov 19 '17 at 10:08
  • Is it possible to change the background color for all the cards in the stack – Kalyan Kumar Nov 19 '17 at 10:17
  • Sure. All you need is a selector that will give you all of the elements that represent the card, then set the `backgroundColor` on all of them. Something like: `var els = document.querySelectorAll('some very specific selector for the cards'); els.forEach((el) => { el.style.backgroundColor = '#00DD00'; })` **Notice the use of `querySelectorAll` instead of `querySelector`** – Intervalia Nov 19 '17 at 18:18