Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add CSS property to a class by JavaScript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to do this?

const elm  = document.querySelector('.test');
.test {
  width: 200px;
  height: 50px;
  background-color: orange;
}
<div class="test">Testing...123</div>

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading