0

How do I add new CSS property to an existing class?

For example, if I got a class name .test and already have some styling/properties.

And I'd like to add a new property color: blue; to this class name by JavaScript.

How to do this?

const elm  = document.querySelector('.test');
.test {
  width: 200px;
  height: 50px;
  background-color: orange;
}
<div class="test">Testing...123</div>
nakar20966
  • 123
  • 9
  • Also see [modify a css rule object with javascript](https://stackoverflow.com/questions/13528512/modify-a-css-rule-object-with-javascript); MDN [CSSStyleSheet.cssRules](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/cssRules) – showdev Apr 13 '22 at 03:23

1 Answers1

0

You can search all css rules and find the one with selector of .test, then add any property to the rule.

let target;

outer: for(let sheet of document.styleSheets) {
  for(let rule of sheet.rules) {
    if(rule.selectorText === '.test') {
      target = rule;
      break outer;
    }
  }
}

if(target) {
  target.style.color = 'blue';
}
.test {
  width: 200px;
  height: 50px;
  background-color: orange;
}
<div class="test">Testing...123</div>
<div class="test">Testing...456</div>
Hao Wu
  • 17,573
  • 6
  • 28
  • 60