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