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>

1

1 Answer 1

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>

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

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.