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

15
  • Sounds like an XY problem. What are you trying to achieve? Commented Apr 2, 2019 at 6:09
  • 1
    document.getElementById("gmType").style.backgroundColor="red"; or document.querySelector(".gmBox").style.backgroundColor="red"; AFTER the element has loaded Commented Apr 2, 2019 at 6:12
  • 1
    While OP might be satisfied with an Y answer to their X question, the question itself is not a duplicate to the link it was closed with. Kamil Kiełczewski actually answered the question as asked, and it is interesting in its own right (though few-to-none should have need to do so). Commented Apr 2, 2019 at 6:20
  • 1
    @Vishwa why? - OP did not flag it jQuery Commented Apr 2, 2019 at 6:28
  • 1
    @RobbyCornelissen this is my jquery: let $ = s => document.querySelector(s); :P Commented Apr 2, 2019 at 7:43

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Dupe of stackoverflow.com/questions/13528512/…, which would benefit from your entry
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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.