-1

I would like to change color from div class. I searched the net for some info, but it's not working for me.

I have css style class in which I have property background-color, and I want to change this property from JS file.

I want in class gmBox change background-color:, how I can do this, from JS file?

.gmBox {
  vertical-align: middle;
  padding: 10px;
  margin: 5px;
  background-color: yellow;
  color: black;
  font-size: 23px;
  border-radius: 5px;
}
<div class="gmBox" id="gmType">GM12</div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
qunz666
  • 310
  • 3
  • 15

2 Answers2

2

To change class you need to edit document styles

[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.gmBox')
    .style['background-color']='red';

[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.gmBox').style['background-color']='red';
.gmBox {
vertical-align: middle;
padding: 10px;
margin: 5px;
background-color: yellow;
color: black;
font-size: 23px;
border-radius: 5px;
}
<div class="gmBox" id="gmType">GM12</div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 1
    Dupe of https://stackoverflow.com/questions/13528512/modify-a-css-rule-object-with-javascript, which would benefit from your entry – mplungjan Apr 02 '19 at 06:26
0

Try doing this (button added just to show the toggling effect):

$("#toggle").on("click", function(){
  $(".gmBox").toggleClass("toggleBgColor");
})
.gmBox {
  vertical-align: middle;
  padding: 10px;
  margin: 5px;
  background-color: yellow;
  color: black;
  font-size: 23px;
  border-radius: 5px;
}
.toggleBgColor {
   background-color: blue;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gmBox" id="gmType">GM12</div>
<button id="toggle">Click me to toggle!!!</button>
alimbaronia
  • 504
  • 2
  • 10